Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

33 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

README.md for J2EE Design Patterns Demo (OODP1 Package)

๐Ÿ—๏ธ J2EE Design Patterns Showcase (OODP1)

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.


๐Ÿ“‘ Table of Contents

  1. โœจ Project Overview

  2. ๐Ÿ“‚ OODP1 Package Structure

  3. ๐Ÿš€ How to Run Demos

  4. ๐Ÿ” Pattern Demonstrations

  5. ๐Ÿ“ Exercises & Extensions

  6. ๐Ÿ“Œ OODP2 Package (Upcoming)

  7. ๐Ÿค Contribution

  8. ๐Ÿ“œ License


โœจ Project Overview

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.


๐Ÿ“‚ OODP1 Package Structure

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

๐Ÿš€ How to Run Demos

  1. Compile the project with Maven or your IDE.

  2. Execute a demoโ€™s main() method. For Maven:

    mvn compile exec:java -Dexec.mainClass="com.tharindu.oodp1.Adapter.MainAdapter"
  3. Review console output illustrating pattern behavior.


๐Ÿ” Pattern Demonstrations

Here is the complete README.md converted from your Design Pattern Scenarios.docx, formatted in Markdown:


๐ŸŽจ Design Pattern Scenarios

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.


๐Ÿ”’ Singleton Design Pattern: Printer Spooler

๐Ÿ“˜ Scenario

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

โœ… Real-World Benefit

  • Centralized control
  • Prevents duplicate access
  • Improves reliability

singleton

๐Ÿ–จ๏ธ Output

Printer Spooler Initialized
Printing: Employee Report.pdf
Printing: Annual Budget.xlsx

๐ŸŽญ Facade Design Pattern: ๐Ÿฟ Home Theater System

๐Ÿ“˜ Scenario

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.

facade

๐ŸŽฌ Output

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...

๐ŸŽฏ Strategy Design Pattern: ๐Ÿฆ Online Payment System

๐Ÿ“˜ Scenario

Users can pay via:

  • ๐Ÿ’ณ Credit Card
  • ๐Ÿ’ธ PayPal
  • ๐Ÿ’ฐ Cryptocurrency

Each has its own logic.

โŒ Problem

A single PaymentProcessor with if-else becomes unmaintainable.

๐Ÿ’ก Solution

Use a common interface and plug in a strategy at runtime.

Strategy

๐Ÿ’ต Output

Paid Rs. 1500.0 using Credit Card.
Paid Rs. 5000.0 using PayPal.
Paid Rs. 12000.0 using Cryptocurrency.

๐Ÿ”Œ Adapter Design Pattern: โšก Charging a Phone in Europe

๐Ÿ“˜ Scenario

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.

๐Ÿ”ง Design Mapping

Element Role
Phone Client
EuropeanSocket Target Interface
USCharger Adaptee
PlugAdapter Adapter

Adapter

๐Ÿ”‹ Output

Phone starts charging...
Adapting plug...
Power supplied using US standard plug.

๐Ÿญ Factory Design Pattern: ๐ŸŽฎ Battle Sim VR

๐Ÿ“˜ Scenario

A military VR sim equips recruits using a GunFactory. You ask, it delivers:

๐Ÿ”ง Missions

  • Urban Ambush โ†’ Pistol
  • Frontline Warzone โ†’ Rifle + Shotgun
  • Jungle Siege โ†’ AK47 + Sniper Rifle

Factory

๐Ÿ”ซ Output

=== Weapon Test Firing ===
1๏ธโƒฃ Firing Pistol:
ฬธฬธฬฑอ‚ ฬธอ†ฬฟอž ฬ„ฬฟฬ„อž ฬฟฬ…อž ฬฟฬ…อž ฬ„ฬš

2๏ธโƒฃ Firing Rifle:
โ–„๏ธปใƒ‡โ•ฆโ•ไธ€โ”

3๏ธโƒฃ Firing Shotgun:
โŒโ•ฆโ•ฆโ•โ”€

4๏ธโƒฃ Firing AK47:
โ–„๏ธปโ•ฆ่Šซโ‰กโ•โ•--

5๏ธโƒฃ Firing Sniper Rifle:
๏ธปโ•ฆฬตฬตฬฟโ•คโ”โ”€

=== All weapons fired! ===

๐ŸŒ Proxy Design Pattern: ๐Ÿ” Secure Vault Operator

๐Ÿ“˜ Scenario

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.

๐Ÿ›ก๏ธ Mapping

Story Element Java Component
Real vault system RealDatabase
Proxy ProxyDatabase
Auth check authenticate()

Proxy

๐Ÿ”‘ Output

=== 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.

๐Ÿข Template Method Pattern: Realm Defenders Ritual

๐Ÿ“˜ Scenario

Heroes follow a fixed battle ritual:

  1. Prepare
  2. Engage
  3. Defend
  4. Celebrate

Different hero types (Warrior, Mage, Archer) override only the parts that differโ€”in exactly the order defined by the ritual.

TemplateMethod

๐Ÿ›ก๏ธ Output

=== 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.

๐Ÿ” Iterator Design Pattern: ๐ŸŽง DJ Mixer Playlist

๐Ÿ“˜ Scenario

  • 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.

Iterator

๐ŸŽต Output

=== DJ Playlist ===
Now playing: "Levels" by Avicii
Now playing: "Strobe" by deadmau5

๐Ÿ” Observer Design Pattern: ๐Ÿ•ต๏ธโ€โ™‚๏ธ The Whistling Typewriter

๐Ÿ“˜ Scenario

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

Observer

๐Ÿงพ Output

[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]

๐Ÿ“Š State Design Pattern: ๐ŸŽฎ Shadow Ops โ€” Stealth Guard AI

๐Ÿ“˜ Scenario

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.

State

๐Ÿง  Output

[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.

โšœ๏ธ Command Design Pattern: ๐Ÿฆธ๐Ÿปโ€โ™€๏ธ Crisis at Metropolis

๐Ÿ“˜ Scenario

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.

Command

๐Ÿงจ Output

=== 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!

๐Ÿ“ Exercises & Extensions

  • Implement OODP2 patterns in the java/com/tharindu/oodp2/ package.
  • Add JEE interceptors to log demo executions automatically.

๐Ÿ“Œ OODP2 Package (Upcoming)

java/com/tharindu/oodp2/
โ”œโ”€โ”€ Builder/
โ”œโ”€โ”€ Decorator/
โ”œโ”€โ”€ Composite/
โ”œโ”€โ”€ ChainOfResponsibility/
โ”œโ”€โ”€ Flyweight/
โ”œโ”€โ”€ Prototype/
โ””โ”€โ”€ Visitor/

Patterns to be documented once implementations complete.


๐Ÿค Contribution

Fork, branch, commit, and send a pull request. Follow Java conventions and include tests.


๐Ÿ“œ License

MIT ยฉ 2025 Tharindu714


Learn by doingโ€”primary design patterns with real code examples! ๐Ÿš€

About

A hands-on collection of foundational Object-Oriented Design Patterns implemented in Java.

Topics

Resources

Stars

Watchers

Forks

Contributors

Languages