A hands-on collection of foundational Object-Oriented Design Patterns implemented in Java. Each pattern features a real-world scenario, UML-conformant code, and execution output.
The OODP1 package illustrates 11 key design patterns with:
- Real-world scenarios and benefits drawn from the domain (e.g., printing, home theater, legal services).
- Java implementations following standard UML structures.
- Demo runners showing console output for each pattern.
All examples reside under java/com/tharindu/oodp1/, ready to compile and execute.
java/com/tharindu/oodp1/
โโโ Adapter/
โโโ LaptopAdapter.java
โ โโโ MainAdapter.java
โโโ Command/
โ โโโ CommandPatternDemo.java
โโโ Facade/
โ โโโ MovieNightFacade.java
โโโ Factory/
โ โโโ MyLegalFactory.java
โโโ Iterator/
โ โโโ IteratorDemo.java
โโโ Observer/
โ โโโ ObserverDemo.java
โโโ Proxy/
โ โโโ MainProxy.java
โโโ Singleton/
โ โโโ OfficeSingleton.java
โโโ State/
โ โโโ StatePatternDemo.java
โโโ Strategy/
โโโ Navigation_Strategy.java
โโโ OnlineStoreStrategy.java
โ โโโ Payment_Strategy.java
โโโ Template/
โโโ TemplateMethodDemo.java
-
Compile the project with Maven or your IDE.
-
Execute a demoโs
main()method. For Maven:mvn compile exec:java -Dexec.mainClass="com.tharindu.oodp1.Adapter.MainAdapter" -
Review console output illustrating pattern behavior.
Here is the complete README.md converted from your Design Pattern Scenarios.docx, formatted in Markdown:
Explore real-world inspired examples of popular design patterns in software development. Each scenario includes a short narrative, the key design concept, and output behavior.
In an office network with multiple computers, direct simultaneous access to the printer would cause conflicts. A Printer Spooler:
- Queues the print jobs
- Sends them one at a time
- Must be a single instance
- Centralized control
- Prevents duplicate access
- Improves reliability
Printer Spooler Initialized
Printing: Employee Report.pdf
Printing: Annual Budget.xlsx
To watch a movie, users have to:
- Turn on TV & Sound System
- Adjust input/volume
- Dim lights
- Start DVD
Too complex? The Facade simplifies it.
Get ready to watch a movie...
Lights dimmed
TV turned on
TV input set to HDMI
Sound system on
Volume set to 10
DVD Player on
Playing movie: Avengers: Endgame
Shutting down the theater...
Users can pay via:
- ๐ณ Credit Card
- ๐ธ PayPal
- ๐ฐ Cryptocurrency
Each has its own logic.
A single PaymentProcessor with if-else becomes unmaintainable.
Use a common interface and plug in a strategy at runtime.
Paid Rs. 1500.0 using Credit Card.
Paid Rs. 5000.0 using PayPal.
Paid Rs. 12000.0 using Cryptocurrency.
You're in Europe with a US laptop charger or phone charger.
- โก Europe uses Type C plugs (2 round pins).
- ๐Your charger has a Type A plug (2 flat pins).
You canโt plug it directly โ so you use a plug adapter.
๐The adapter converts the interface (plug type) so the device (your charger) can work with the existing system (European socket).
Use a Plug Adapter to convert interfaces.
| Element | Role |
|---|---|
| Phone | Client |
| EuropeanSocket | Target Interface |
| USCharger | Adaptee |
| PlugAdapter | Adapter |
Phone starts charging...
Adapting plug...
Power supplied using US standard plug.
A military VR sim equips recruits using a GunFactory. You ask, it delivers:
- Urban Ambush โ Pistol
- Frontline Warzone โ Rifle + Shotgun
- Jungle Siege โ AK47 + Sniper Rifle
=== Weapon Test Firing ===
1๏ธโฃ Firing Pistol:
ฬธฬธฬฑอ ฬธอฬฟอ ฬฬฟฬอ ฬฟฬ
อ ฬฟฬ
อ ฬฬ
2๏ธโฃ Firing Rifle:
โ๏ธปใโฆโไธโ
3๏ธโฃ Firing Shotgun:
โโฆโฆโโ
4๏ธโฃ Firing AK47:
โ๏ธปโฆ่ซโกโโ--
5๏ธโฃ Firing Sniper Rifle:
๏ธปโฆฬตฬตฬฟโคโโ
=== All weapons fired! ===
In a high-tech research facility, there's a secure vault that stores classified information. Only a trusted operator named Tharindu knows how to safely interact with the vault's delicate system (insert, update, delete, read).
However, allowing everyone to directly touch the vault system is risky. What if someone enters the wrong command? Or worse โ tries to steal data?
To solve this, the facility appoints a gatekeeper โ a Proxy Operator. The gatekeeper looks like a regular operator to others, but before doing anything, he asks for a username and password.
If you give the correct credentials, the proxy lets you through to the real vault system and performs the operation.
If not, the proxy denies access and logs the intrusion attempt.
So now, people can ask to insert, update, delete, or query the database, but only if they go through the proxy. The real vault stays hidden and safe behind this protective layer.
| Story Element | Java Component |
|---|---|
| Real vault system | RealDatabase |
| Proxy | ProxyDatabase |
| Auth check | authenticate() |
=== Attempt with valid credentials ===
[ProxyDatabase] Authenticated. Delegating insert().
[RealDatabase] Inserting data into the database.
[ProxyDatabase] Authenticated. Delegating update().
[RealDatabase] Updating data in the database.
[ProxyDatabase] Authenticated. Delegating delete().
[RealDatabase] Deleting data from the database.
[ProxyDatabase] Authenticated. Delegating select().
[RealDatabase] Selecting data with query: SELECT * FROM users
=== Attempt with invalid credentials ===
[ProxyDatabase] Authentication failed. Access denied.
[ProxyDatabase] Authentication failed. Access denied.
[ProxyDatabase] Authentication failed. Access denied.
[ProxyDatabase] Authentication failed. Access denied.
Heroes follow a fixed battle ritual:
- Prepare
- Engage
- Defend
- Celebrate
Different hero types (Warrior, Mage, Archer) override only the parts that differโin exactly the order defined by the ritual.
=== Warriorโs Ritual ===
[Warrior] Donning heavy armor and readying sword.
[Warrior] Charges forward with a battle cry!
[Warrior] Raises shield to block incoming blows.
[Warrior] Roars victoriously and pounds chest.
=== Mageโs Ritual ===
[Mage] Chanting incantations and gathering mana.
[Mage] Hurls a blazing fireball at the enemy!
[Mage] Conjures a shimmering magical barrier.
=== Archerโs Ritual ===
[Archer] Nocking arrow and adjusting quiver.
[Archer] Fires a volley of arrows with deadly precision.
[Archer] Dodges and keeps distance from foes.
[Archer] Salutes enemy before vanishing into the trees.
- A DJโs application manages multiple playlists (e.g. โHouse Classicsโ, โChill Vibesโ).
- Internally each playlist may store songs in different ways (array, ArrayList, etc.), but the DJ just wants to step through each song in orderโno matter how itโs stored.
- The Iterator pattern gives you a uniform way to traverse any playlist without exposing its internal structure.
=== DJ Playlist ===
Now playing: "Levels" by Avicii
Now playing: "Strobe" by deadmau5
In Victorian London, Detective Marlowe is hunting a ghost who types cryptic messages on an antique typewriter in an abandoned manor. Every time the phantom strikes a new key, three specialists swarm in:
- ๐งช Forensic Analyst
- ๐ฎ Psychic Medium
- ๐ป Tech Geek
[CrimeScene] New clue discovered: "MURDER AT MIDNIGHT"
๐งช ForensicAnalyst: Dusting the keys for prints on clue โ MURDER AT MIDNIGHT
๐ฎ PsychicMedium: I hear whispers chanting 'MURDER AT MIDNIGHT'!
๐ป TechGeek: Arduino logged keystroke sequence: [MURDER AT MIDNIGHT]
[CrimeScene] New clue discovered: "LOOK UNDER THE FLOORBOARD"
๐งช ForensicAnalyst: Dusting the keys for prints on clue โ LOOK UNDER THE FLOORBOARD
๐ฎ PsychicMedium: I hear whispers chanting 'LOOK UNDER THE FLOORBOARD'!
๐ป TechGeek: Arduino logged keystroke sequence: [LOOK UNDER THE FLOORBOARD]
[CrimeScene] New clue discovered: "THE BUTLER DID IT"
๐งช ForensicAnalyst: Dusting the keys for prints on clue โ THE BUTLER DID IT
๐ฎ PsychicMedium: I hear whispers chanting 'THE BUTLER DID IT'!
๐ป TechGeek: Arduino logged keystroke sequence: [THE BUTLER DID IT]
Drones switch states on the fly:
- Patrol โ scan area
- Alert โ investigate threat
- Attack โ shoot at intruder
As events happenโโseeEnemyโ, โhearNoiseโ, โloseEnemyโ, โenemyInRangeโโthe drone switches its internal state and its behavior changes accordingly. The State Pattern lets us encapsulate each modeโs logic in its own class and switch at runtime without huge if/else chains.
[PatrolState] Guard is patrolling the area.
[PatrolState] Intruder spotted! Switching to ALERT state.
[AlertState] Guard is taking cover and surveying the area.
[AlertState] Target in range! Switching to ATTACK state.
[AttackState] Guard is engaging the enemy aggressively.
[AttackState] Target escaped! Switching to PATROL state.
[PatrolState] Guard is patrolling the area.
The Justice League Command Center has a Control Panel (Invoker) with buttons for different mission types. Each button stores a Command object encapsulating the action and the target hero (Receiver). When a crisis hits, the panel simply โpressesโ the appropriate button, and the corresponding hero executes their mission.
=== Crisis: Alien Drone Attack ===
[ControlPanel] Activating command...
[Superman] Flying at hypersonic speed to Metropolis!
[Superman] Rescuing civilians from collapsing buildings!
=== Crisis: Jokerโs Drone Swarm ===
[ControlPanel] Activating command...
[Batman] Launching Batarang to disable the drone swarm!
=== Crisis: Collapsed Subway Tunnel ===
[ControlPanel] Activating command...
[Flash] Speed-blur rescuing victims in seconds!
- Implement OODP2 patterns in the
java/com/tharindu/oodp2/package. - Add JEE interceptors to log demo executions automatically.
java/com/tharindu/oodp2/
โโโ Builder/
โโโ Decorator/
โโโ Composite/
โโโ ChainOfResponsibility/
โโโ Flyweight/
โโโ Prototype/
โโโ Visitor/
Patterns to be documented once implementations complete.
Fork, branch, commit, and send a pull request. Follow Java conventions and include tests.
MIT ยฉ 2025 Tharindu714
Learn by doingโprimary design patterns with real code examples! ๐










