Welcome to the Java Design Patterns Examples repository! This project demonstrates key design patterns in Java through real-world examples. It is ideal for learning Object-Oriented Programming (OOP) design principles.
- Patterns Implemented
- Singleton Pattern
- Decorator Pattern
- Observer Pattern
- Code Examples and Insights
- How to Run
- Contributing
- License
- Singleton Pattern: Ensures a class has only one instance and provides a global point of access to it.
- Decorator Pattern: Allows behavior to be added to individual objects, dynamically, without affecting the behavior of other objects from the same class.
- Observer Pattern: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The Singleton pattern is demonstrated through a database connection manager.
- Class:
DatabaseConnection - Example Usage:
DatabaseConnectiondb1 = DatabaseConnection.getInstance(); DatabaseConnectiondb2 = DatabaseConnection.getInstance(); db1.query("SELECT * FROM users"); db2.query("INSERT INTO users VALUES (1, 'John')");
The Decorator pattern is demonstrated through a customizable coffee shop.
- Classes:
SimpleCoffee,MilkDecorator,SugarDecorator - Example Usage:
Coffeecoffee = newSimpleCoffee(); coffee = newMilkDecorator(coffee); coffee = newSugarDecorator(coffee); System.out.println(coffee.getDescription() + " $" + coffee.getCost());
The Observer pattern is demonstrated through a weather monitoring system.
- Classes:
WeatherStation,CurrentConditionsDisplay,StatisticsDisplay - Example Usage:
WeatherStationweatherStation = newWeatherStation(); weatherStation.registerObserver(newCurrentConditionsDisplay()); weatherStation.registerObserver(newStatisticsDisplay()); weatherStation.setTemperature(80);
Singleton Pattern Overview 🔒🌐
The Singleton Pattern ensures that a class has only one instance and provides a global point of access to that instance. This pattern is useful when exactly one object is needed to coordinate actions across the system.
In many applications, you need to ensure that only one instance of a database connection is created to prevent resource conflicts and manage resources efficiently. The Singleton pattern ensures that there is only one instance of a class and provides a global point of access to it.
privatestaticDatabaseConnectioninstance;- This variable holds the single instance of the class.
- Being
staticmeans it belongs to the class, not to any specific object of the class.
privateDatabaseConnection() {
System.out.println("Database Connection established");
}- The constructor is private, preventing other classes from instantiating the
DatabaseConnectionclass directly. - It ensures that the only way to get an instance of this class is through the
getInstancemethod.
publicstaticDatabaseConnectiongetInstance() {
if (instance == null) {
instance = newDatabaseConnection();
}
returninstance;
}- This method returns the single instance of the class.
- If the
instanceisnull(meaning it hasn't been created yet), it creates a new instance. - Subsequent calls to
getInstancereturn the already created instance, ensuring there's only one instance.
publicvoidquery(Stringsql) {
System.out.println("Executing query: " + sql);
}- This method simulates executing a database query.
- It prints out the SQL query string provided as an argument.
DatabaseConnectiondb1 = DatabaseConnection.getInstance();
DatabaseConnectiondb2 = DatabaseConnection.getInstance();- Both
db1anddb2are references to the same instance ofDatabaseConnection. - The
getInstancemethod ensures that the same instance is returned both times.
db1.query("SELECT * FROM users");
db2.query("INSERT INTO users VALUES (1, 'John')");- The
querymethod is called on bothdb1anddb2. - Since
db1anddb2refer to the same instance, these calls operate on the same object.
System.out.println(db1 == db2);- This prints
truebecausedb1anddb2are references to the same instance.
When running the Main class, the final output will be:
DatabaseConnectionestablishedExecutingquery: SELECT * FROMusersExecutingquery: INSERTINTOusersVALUES (1, 'John')
true- Database Connection established is printed once when the instance is first created by
DatabaseConnection.getInstance(). - Executing query: SELECT * FROM users is printed after called the
db1.query("SELECT * FROM users"). - Executing query: INSERT INTO users VALUES (1, 'John') is printed when
db2.query("INSERT INTO users VALUES (1, 'John')")is called. - true is printed when
System.out.println(db1 == db2)is executed, confirming that both references point to the same instance.
Decorator Pattern Overview 🎨✨
The Decorator Pattern allows behavior to be added to individual objects, either statically or dynamically, without affecting the behavior of other objects from the same class. This pattern is typically used to extend the functionalities of classes in a flexible and reusable way.
In a coffee shop, you can order a basic coffee and add various add-ons like milk or sugar. The Decorator pattern allows you to add behavior to objects dynamically.
Coffee Interface defines the structure that all coffee types (both base and decorated) must follow.
interfaceCoffee {
StringgetDescription();
doublegetCost();
}- The
getDescription()method returns a description of the coffee. - It implemented by both base and decorator classes.
- The
getCost()method returns the cost of the coffee. - It also implemented by both base and decorator classes.
SimpleCoffee Class represents a basic coffee without any decorations.
classSimpleCoffeeimplementsCoffee {
@OverridepublicStringgetDescription() {
return"Simple Coffee";
}
@OverridepublicdoublegetCost() {
return5.0;
}
}- The
getDescription()method returns Simple Coffee. - The
getCost()Method returns a base cost of 5.0.
CoffeeDecorator Abstract Class implements the Coffee interface and serves as the base class for all coffee decorators.
abstractclassCoffeeDecoratorimplementsCoffee {
protectedCoffeedecoratedCoffee;
publicCoffeeDecorator(Coffeecoffee) {
this.decoratedCoffee = coffee;
}
publicStringgetDescription() {
returndecoratedCoffee.getDescription();
}
publicdoublegetCost() {
returndecoratedCoffee.getCost();
}
}- The
decoratedCoffeefield holds the reference to the coffee object being decorated. - The constructor initializes the
decoratedCoffeewith the givencoffee. - The
getDescription()method returns the description of the decorated coffee. - The
getCost()method returns the cost of the decorated coffee.
MilkDecorator Class adds milk to the coffee, extending the CoffeeDecorator.
classMilkDecoratorextendsCoffeeDecorator {
publicMilkDecorator(Coffeecoffee) {
super(coffee);
}
@OverridepublicStringgetDescription() {
returndecoratedCoffee.getDescription() + " + Milk";
}
@OverridepublicdoublegetCost() {
returndecoratedCoffee.getCost() + 1.5;
}
}- The constructor passes the coffee to be decorated to the
CoffeeDecoratorconstructor. - The
getDescription()method appends + Milk to the existing description. - The
getCost()method adds 1.5 to the existing cost.
SugarDecorator Class adds sugar to the coffee, extending the CoffeeDecorator.
classSugarDecoratorextendsCoffeeDecorator {
publicSugarDecorator(Coffeecoffee) {
super(coffee);
}
@OverridepublicStringgetDescription() {
returndecoratedCoffee.getDescription() + " + Sugar";
}
@OverridepublicdoublegetCost() {
returndecoratedCoffee.getCost() + 0.5;
}
}- The constructor passes the coffee to be decorated to the
CoffeeDecoratorconstructor. - The
getDescription()method appends + Sugar to the existing description. - The
getCost()method adds 0.5 to the existing cost.
Main Class demonstrates the use of the decorators to add features to the base coffee.
publicclassMain {
publicstaticvoidmain(String[] args) {
Coffeecoffee = newSimpleCoffee();
System.out.println(coffee.getDescription() + " $" + coffee.getCost());
coffee = newMilkDecorator(coffee);
System.out.println(coffee.getDescription() + " $" + coffee.getCost());
coffee = newSugarDecorator(coffee);
System.out.println(coffee.getDescription() + " $" + coffee.getCost());
}
}Creating a Simple Coffee:
Coffeecoffee = newSimpleCoffee();
System.out.println(coffee.getDescription() + " $" + coffee.getCost());- This creates a
SimpleCoffeeinstance. - It prints the description and cost: Simple Coffee $5.0.
Adding Milk to Coffee:
coffee = newMilkDecorator(coffee);
System.out.println(coffee.getDescription() + " $" + coffee.getCost());- This decorates the
coffeewithMilkDecorator. - It prints the new description and cost: Simple Coffee + Milk $6.5.
Adding Sugar to Coffee:
coffee = newSugarDecorator(coffee);
System.out.println(coffee.getDescription() + " $" + coffee.getCost());- This further decorates the
coffeewithSugarDecorator. - It prints the new description and cost: Simple Coffee + Milk + Sugar $7.0.
The Final Output generated as follows:
SimpleCoffee$5.0SimpleCoffee + Milk$6.5SimpleCoffee + Milk + Sugar$7.0When the Main class is executed, it follows these steps to generate the output:
1. Creating a Simple Coffee:
Coffeecoffee = newSimpleCoffee();
System.out.println(coffee.getDescription() + " $" + coffee.getCost());- A
SimpleCoffeeinstance is created. - The
getDescription()method ofSimpleCoffeereturns Simple Coffee. - The
getCost()method of Simpl`eCoffee returns 5.0. - The output is: Simple Coffee $5.0.
2. Adding Milk to Coffee:
coffee = newMilkDecorator(coffee);
System.out.println(coffee.getDescription() + " $" + coffee.getCost());- The
SimpleCoffeeinstance is decorated withMilkDecorator. - The
getDescription()method ofMilkDecoratorcalls thegetDescription()method of the decorated coffee (which isSimpleCoffee) and appends + Milk. - The
decoratedCoffee.getDescription()returns Simple Coffee. - Then the final description is Simple Coffee + Milk.
- The
getCost()method ofMilkDecoratorcalls thegetCost()method of the decorated coffee (which isSimpleCoffee) and adds 1.5. - In this case, the
decoratedCoffee.getCost()returns 5.0. - After that, the final cost is 5.0 + 1.5 = 6.5.
- Then the output is: Simple Coffee + Milk $6.5.
3. Adding Sugar to Coffee:
coffee = newSugarDecorator(coffee);
System.out.println(coffee.getDescription() + " $" + coffee.getCost());- The
MilkDecoratorinstance (which already decoratesSimpleCoffee) is further decorated withSugarDecorator. - The
getDescription()method ofSugarDecoratorcalls thegetDescription()method of the decorated coffee (which isMilkDecorator) and appends + Sugar. - In here the
decoratedCoffee.getDescription()(which isMilkDecorator.getDescription()) returns Simple Coffee + Milk. - So the final description is Simple Coffee + Milk + Sugar.
- After that, the
getCost()method ofSugarDecoratorcalls thegetCost()method of the decorated coffee (which isMilkDecorator) and adds 0.5. - In that case, the
decoratedCoffee.getCost()(which isMilkDecorator.getCost()) returns 6.5. - So the, final cost is 6.5 + 0.5 = 7.0.
- Finally, the output is: Simple Coffee + Milk + Sugar $7.0.
Observer Pattern Overview 👀📡
The Observer pattern allows you to define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Imagine a weather station that monitors temperature and updates multiple displays whenever the temperature changes.
WeatherSubject Interface defines the methods that any subject (in this case, a weather station) must implement to allow observers to register, unregister, and be notified of changes.
interfaceWeatherSubject {
voidregisterObserver(WeatherObserverobserver);
voidremoveObserver(WeatherObserverobserver);
voidnotifyObservers();
}- The
registerObserver()method adds an observer to the list of observers. - The
removeObserver()method removes an observer from the list of observers. - The
notifyObservers()method notifies all registered observers of a change.
WeatherStation Class implements the WeatherSubject interface and maintains a list of observers. It also holds the temperature data and notifies observers when the temperature changes.
classWeatherStationimplementsWeatherSubject {
privateList<WeatherObserver> observers;
privatefloattemperature;
publicWeatherStation() {
this.observers = newArrayList<>();
}
@OverridepublicvoidregisterObserver(WeatherObserverobserver) {
observers.add(observer);
}
@OverridepublicvoidremoveObserver(WeatherObserverobserver) {
observers.remove(observer);
}
@OverridepublicvoidnotifyObservers() {
for (WeatherObserverobserver : observers) {
observer.update(temperature);
}
}
publicvoidsetTemperature(floattemperature) {
this.temperature = temperature;
notifyObservers();
}
}- The
observersfield is a list to keep track of registered observers. - The
temperaturefield shows the current temperature. - The
registerObserver()method adds anobserverto the list. - The
removeObserver()method removes anobserverfrom the list. - The
notifyObservers()method calls theupdate()method on each registeredobserver, passing the currenttemperature. - The
setTemperature()method sets the temperature and callsnotifyObservers()` method to update all observers.
WeatherObserver Interface defines the update() method that observers must implement to get updates from the subject.
interfaceWeatherObserver {
voidupdate(floattemperature);
}- The
update()method takes the newtemperatureas an argument and updates the observer.
CurrentConditionsDisplay Class implements the WeatherObserver interface and displays the current temperature.
classCurrentConditionsDisplayimplementsWeatherObserver {
@Overridepublicvoidupdate(floattemperature) {
System.out.println("Current conditions: " + temperature + "F degrees");
}
}- The
update()method prints the currenttemperatureto the console.
StatisticsDisplay Class implements the WeatherObserver interface and maintains statistics about the temperature (average, maximum, and minimum).
classStatisticsDisplayimplementsWeatherObserver {
privatefloatmaxTemp = 0.0f;
privatefloatminTemp = 200;
privatefloattempSum = 0.0f;
privateintnumReadings;
@Overridepublicvoidupdate(floattemperature) {
tempSum += temperature;
numReadings++;
if (temperature > maxTemp) {
maxTemp = temperature;
}
if (temperature < minTemp) {
minTemp = temperature;
}
display();
}
publicvoiddisplay() {
System.out.println("Avg/Max/Min temperature = " + (tempSum / numReadings)
+ "/" + maxTemp + "/" + minTemp);
}
}- The following is how the fields are shown in this instance:
maxTemp: Stores the maximum recorded temperature.minTemp: Stores the minimum recorded temperature.tempSum: Stores the sum of all recorded temperatures.numReadings: Counts the number of temperature readings.
- The
update()method updates the statistics with the newtemperatureand calls display. - The
display()method prints the average, maximum, and minimum temperatures to the console.
Main Class demonstrates the Observer Pattern by creating a WeatherStation, registering observers, and changing the temperature.
publicclassMain {
publicstaticvoidmain(String[] args) {
WeatherStationweatherStation = newWeatherStation();
CurrentConditionsDisplaycurrentDisplay = newCurrentConditionsDisplay();
StatisticsDisplaystatisticsDisplay = newStatisticsDisplay();
weatherStation.registerObserver(currentDisplay);
weatherStation.registerObserver(statisticsDisplay);
weatherStation.setTemperature(80);
weatherStation.setTemperature(82);
weatherStation.setTemperature(78);
}
}Creating the WeatherStation:
This creates an instance of
WeatherStation.WeatherStationweatherStation = newWeatherStation();
Creating the Observers:
This creates instances of
CurrentConditionsDisplayandStatisticsDisplay.CurrentConditionsDisplaycurrentDisplay = newCurrentConditionsDisplay(); StatisticsDisplaystatisticsDisplay = newStatisticsDisplay();
Registering the Observers:
This registers the observers with the
WeatherStation.weatherStation.registerObserver(currentDisplay); weatherStation.registerObserver(statisticsDisplay);
Setting the Temperature:
This changes the temperature, which triggers the
notifyObservers()method to update all registered observers.weatherStation.setTemperature(80); weatherStation.setTemperature(82); weatherStation.setTemperature(78);
The Final output is generated as follows:
Currentconditions: 80.0FdegreesAvg/Max/Mintemperature = 80.0/80.0/80.0Currentconditions: 82.0FdegreesAvg/Max/Mintemperature = 81.0/82.0/80.0Currentconditions: 78.0FdegreesAvg/Max/Mintemperature = 80.0/82.0/78.0When the Main class is executed, it follows these steps to generate the output:
1. Setting the temperature to 80:
- The
CurrentConditionsDisplayprints: Current conditions: 80.0F degrees. - The
StatisticsDisplayupdates its statistics as:- Average: 801=80.0\frac{80}{1} = 80.0180=80.0
- Maximum: 80.0
- Minimum: 80.0
- Prints: Avg/Max/Min temperature = 80.0/80.0/80.0
2. Setting the temperature to 82:
- The
CurrentConditionsDisplayprints: Current conditions: 82.0F degrees. - The
StatisticsDisplayupdates its statistics as:- Average: 80+822=81.0\frac{80 + 82}{2} = 81.0280+82=81.0
- Maximum: 82.0
- Minimum: 80.0
- Prints: Avg/Max/Min temperature = 81.0/82.0/80.0
3. Setting the temperature to 78:
- The
CurrentConditionsDisplayprints: Current conditions: 78.0F degrees. - The
StatisticsDisplayupdates its statistics as:- Average: 80+82+783≈80.0\frac{80 + 82 + 78}{3} \approx 80.0380+82+78≈80.0
- Maximum: 82.0
- Minimum: 78.0
- Prints: Avg/Max/Min temperature = 80.0/82.0/78.0
- Clone the repository:
git clone https://github.com/MenathNDGD/Java-Design-Patterns-Examples.git
- Navigate to the desired pattern directory:
cd"Singleton Pattern"# or "Decorator Pattern", "Observer Pattern"
- Compile and run the
Main.javafile:javac Main.java java Main
Contributions are welcome! Please fork this repository and submit a pull request for any enhancements or bug fixes.
This project is licensed under the MIT License. See the LICENSE file for details.