Tutorial Playlist
Design patterns in Java, including design patterns in microservices, provide easily recognizable and usable object-oriented programming solutions to common problems.
The structure of a design pattern is well arranged into a template format to help the user quickly identify the problem and find its solution in reference to the relationship between the objects and the classes. It is a software template developers use to solve problems they encounter multiple times while designing a software application.
In this tutorial, you will learn about the various types of design patterns, the advantage of using design patterns, and when you should use design patterns. The tutorial will also cover the benefits of various design patterns and examples of the core Java design patterns.
The design patterns in software engineering are classified into the following three sub-categories:
Further classification of the design patterns is given in the table below:
Behavioral Design Pattern | Creational Design Pattern | Structural Design Pattern |
Template pattern | Abstract factory pattern | Bridge pattern |
Chain of responsibility pattern | Factory pattern | Adapter pattern |
Mediator pattern | Prototype pattern | Composite pattern |
Observer pattern | Singleton pattern | Decorator pattern |
Strategy pattern | Builder pattern | Flyweight pattern |
Command pattern | Object pool | Facade pattern |
State pattern | Proxy pattern | |
Visitor pattern | ||
Iterator pattern | ||
Interpretor pattern | ||
Memento pattern |
Behavioral design patterns give solutions based on object interaction. These design patterns recognize and understand common communication patterns among the objects.
Creational design patterns deal with how the objects are being created. Using creational design patterns, you can create objects and the classes associated with them with the least complexity in a controlled fashion. Creational pattern hides the instantiation process of an object and makes the system independent of how objects are composed, created, and represented.
Structural design pattern deals with the organization of the objects and the associated classes and how they are composed to make bigger structures. They are categorized into two categories: structural class patterns and structural object patterns.
There are several benefits of using design patterns. Some of these are as follows:
The following diagram gives an example of how we change a high cohesion code to low cohesion source code:
We should use Design Patterns in the following cases:
We have already covered the objectives of three types of Design Patterns at the beginning of this tutorial. Let us now look at the different types of core Java Design Patterns and understand them with the help of examples.
The Singleton pattern is a popular creational design pattern in Java. The Singleton pattern ensures that only one instance of a class is created and provides a global point of access to it. This can be useful when you want to restrict the instantiation of a class to a single object.
Here is an example of the Singleton creational design pattern:
public class Singleton {
  // Private static instance variable
  private static Singleton instance;
  // Private constructor to prevent instantiation from outside the class
  private Singleton() {
  }
  // Public static method to get the instance of the Singleton class
  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class) {
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
  // Other methods of the Singleton class
  public void someMethod() {
    System.out.println("Singleton method called");
  }
  // Main method to test the Singleton class
  public static void main(String[] args) {
    Singleton singleton = Singleton.getInstance();
    singleton.someMethod();
  }
}
In this example, the class Singleton has a private static instance variable instance, which is the single instance of the class. The constructor is private, preventing the instantiation of the class from outside. The getInstance() method provides the global access point to the instance. It uses double-checked locking to ensure thread safety during the creation of the instance.
In this usage, getInstance() returns the instance of the Singleton class, and you can then call methods on that instance.
One common structural design pattern in Java is the Adapter pattern. The Adapter pattern allows incompatible interfaces to work together by creating a bridge between them. It is useful when you want to make existing classes work with others without modifying their source code.
Here is an example of the Adapter structural design pattern:
(You must make separate .java files for all these portions of code in the same directory in order to run the program.)
// Adaptee (Incompatible interface)
class LegacyRectangle {
  public void draw(int x, int y, int width, int height) {
    System.out.println("LegacyRectangle: draw(x: " + x + ", y: " + y + ", width: " + width + ", height: " + height + ")");
  }
}
// Target (Desired interface)
interface Shape {
  void draw(int x, int y, int width, int height);
}
// Adapter (Adapts the Adaptee to the Target interface)
class RectangleAdapter implements Shape {
  private LegacyRectangle legacyRectangle;
  public RectangleAdapter(LegacyRectangle legacyRectangle) {
    this.legacyRectangle = legacyRectangle;
  }
  @Override
  public void draw(int x, int y, int width, int height) {
    legacyRectangle.draw(x, y, x + width, y + height);
  }
}
// Client
public class Client {
  public static void main(String[] args) {
    // Create an instance of the Adaptee (LegacyRectangle)
    LegacyRectangle legacyRectangle = new LegacyRectangle();
    // Create an instance of the Adapter (RectangleAdapter)
    Shape shape = new RectangleAdapter(legacyRectangle);
    // Use the Adapter to draw a shape
    shape.draw(10, 20, 30, 40);
  }
}
In this example, we have an existing class LegacyRectangle, which represents an incompatible interface. The Shape interface represents the desired interface. The RectangleAdapter class acts as an adapter, implementing the Shape interface and adapting the LegacyRectangle class.
The RectangleAdapter class takes an instance of LegacyRectangle in its constructor and delegates the draw method call to the corresponding method of LegacyRectangle, adapting the arguments if needed.
In the Client class, we create an instance of the LegacyRectangle (the Adaptee) and an instance of the RectangleAdapter (the Adapter). We then use the Shape interface to call the draw method, which internally calls the draw method of the LegacyRectangle class.
The Adapter pattern allows the incompatible LegacyRectangle class to work with the desired Shape interface by using the RectangleAdapter.
Let us take the example of the Observer pattern to understand behavioral design patterns in Java. The Observer pattern defines a one-to-many dependency between objects, where when one object (subject) changes its state, all its dependents (observers) are notified and updated automatically. This pattern promotes loose coupling between objects.
Here is an example of the Observer behavior design pattern:
import java.util.ArrayList;
import java.util.List;
// Subject (Observable)
interface Subject {
  void registerObserver(Observer observer);
  void removeObserver(Observer observer);
  void notifyObservers();
}
// Concrete Subject
class WeatherStation implements Subject {
  private double temperature;
  private List<Observer> observers;
  public WeatherStation() {
    observers = new ArrayList<>();
  }
  public void setTemperature(double temperature) {
    this.temperature = temperature;
    notifyObservers();
  }
  @Override
  public void registerObserver(Observer observer) {
    observers.add(observer);
  }
  @Override
  public void removeObserver(Observer observer) {
    observers.remove(observer);
  }
  @Override
  public void notifyObservers() {
    for (Observer observer : observers) {
      observer.update(temperature);
    }
  }
}
// Observer
interface Observer {
  void update(double temperature);
}
// Concrete Observer
class TemperatureDisplay implements Observer {
  @Override
  public void update(double temperature) {
    System.out.println("Temperature Display: The current temperature is " + temperature + " degrees Celsius");
  }
}
// Client
public class Client {
  public static void main(String[] args) {
    // Create a weather station (subject)
    WeatherStation weatherStation = new WeatherStation();
    // Create temperature display (observer)
    TemperatureDisplay temperatureDisplay = new TemperatureDisplay();
    // Register the temperature display as an observer
    weatherStation.registerObserver(temperatureDisplay);
    // Simulate a temperature change
    weatherStation.setTemperature(25.5);
  }
}
In this example, we have a WeatherStation class representing the subject (observable) that maintains the temperature. It keeps track of a list of observers and notifies them whenever the temperature changes. The TemperatureDisplay class represents an observer that displays the current temperature.
The Subject interface defines methods to register, remove, and notify observers. The Observer interface declares the update method that is called by the subject when a change occurs. The WeatherStation and TemperatureDisplay classes implement the respective interfaces and define the concrete implementations.
In the Client class, we create an instance of the WeatherStation (subject) and the TemperatureDisplay (observer). We register the TemperatureDisplay as an observer to the WeatherStation using the registerObserver method. Finally, we simulate a temperature change by calling the setTemperature method on the WeatherStation, which triggers the notification to the registered observer.
The Observer pattern allows the TemperatureDisplay (observer) to automatically update its display when the WeatherStation (subject) changes its temperature.
This tutorial showed how Java design patterns solve recurring programming problems. You learned the various types of design patterns, namely, behavioral, creational, and structural design patterns. You also learned about the benefit of using design patterns which gives independence to the designer in choosing the suitable platform, solution type, and many more.
You can employ design patterns in software engineering to scale your software, manage complex codes, and provide solutions for recurring issues. In addition to learning from tutorials like these, you can learn more about Java by enrolling in various professional courses from upGrad to grow as a successful future software developer.
1. java.util.iterator is an example of which design pattern?
java.util.iterator is an example of a behavioral pattern.
2. Can a specific design pattern solve all recurring programming issues?
No, design patterns are specific to certain recurring programming issues.
3. Being a novice in Java, is it essential to learn design patterns?
It is not a must, but learning about design patterns will benefit the developer in scaling their problem-solving skills.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...