1.
Creational Patterns
1.1 Singleton Pattern
Description: Ensures a class has only one instance and provides a global point of access to it.
Real-World Example: A database connection pool where only one connection pool object exists
throughout the application.
Java Example:
public class DatabaseConnection {
private static DatabaseConnection instance;
private DatabaseConnection() {}
public static synchronized DatabaseConnection getInstance() {
if (instance == null) {
instance = new DatabaseConnection();
return instance;
public void connect() {
System.out.println("Connected to the database.");
1.2 Factory Method Pattern
Description: Defines an interface for creating objects, but allows subclasses to alter the type of
objects that will be created.
Real-World Example: A document editor that can create different types of documents (e.g.,
Word, PDF) based on user selection.
interface Document {
void open();
class WordDocument implements Document {
public void open() {
System.out.println("Opening Word document.");
class PdfDocument implements Document {
public void open() {
System.out.println("Opening PDF document.");
abstract class DocumentCreator {
public abstract Document createDocument();
public void openDocument() {
Document doc = createDocument();
doc.open();
class WordDocumentCreator extends DocumentCreator {
public Document createDocument() {
return new WordDocument();
}
}
class PdfDocumentCreator extends DocumentCreator {
public Document createDocument() {
return new PdfDocument();
1.3 Abstract Factory Pattern
Description: Provides an interface for creating families of related or dependent objects without
specifying their concrete classes.
Real-World Example: A GUI toolkit that can create buttons and checkboxes for different
operating systems (e.g., Windows, Mac).
// Abstract products
interface Button {
void paint();
interface Checkbox {
void paint();
// Concrete products for Windows
class WindowsButton implements Button {
public void paint() {
System.out.println("Painting Windows button.");
class WindowsCheckbox implements Checkbox {
public void paint() {
System.out.println("Painting Windows checkbox.");
// Concrete products for Mac
class MacButton implements Button {
public void paint() {
System.out.println("Painting Mac button.");
class MacCheckbox implements Checkbox {
public void paint() {
System.out.println("Painting Mac checkbox.");
// Abstract factory
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
// Concrete factories
class WindowsFactory implements GUIFactory {
public Button createButton() {
return new WindowsButton();
}
public Checkbox createCheckbox() {
return new WindowsCheckbox();
class MacFactory implements GUIFactory {
public Button createButton() {
return new MacButton();
public Checkbox createCheckbox() {
return new MacCheckbox();
1.4 Builder Pattern
Description: Separates the construction of a complex object from its representation so that the
same construction process can create different representations.
Real-World Example: Building a car with different options (e.g., color, engine type) using a car
builder.
class Car {
private String color;
private String engineType;
public void setColor(String color) {
this.color = color;
}
public void setEngineType(String engineType) {
this.engineType = engineType;
@Override
public String toString() {
return "Car [color=" + color + ", engineType=" + engineType + "]";
class CarBuilder {
private Car car;
public CarBuilder() {
car = new Car();
public CarBuilder setColor(String color) {
car.setColor(color);
return this;
public CarBuilder setEngineType(String engineType) {
car.setEngineType(engineType);
return this;
public Car build() {
return car;
}
2. Structural Patterns
2.1 Adapter Pattern
Description: Allows an interface to be used in a way that it was not originally intended by
adapting it to a different interface.
Real-World Example: A power adapter that allows devices from different countries to be used
with different electrical outlets.
// Target interface
interface Voltage {
void connect();
// Adaptee
class OldVoltage {
public void connectToOldSocket() {
System.out.println("Connecting to old socket.");
// Adapter
class VoltageAdapter implements Voltage {
private OldVoltage oldVoltage;
public VoltageAdapter(OldVoltage oldVoltage) {
this.oldVoltage = oldVoltage;
}
public void connect() {
oldVoltage.connectToOldSocket();
2.2 Bridge Pattern
Description: Separates an abstraction from its implementation so that the two can vary
independently.
Real-World Example: A remote control that can work with different types of devices (e.g., TV,
stereo).
Java Example:
// Abstraction
abstract class RemoteControl {
protected Device device;
public RemoteControl(Device device) {
this.device = device;
public abstract void powerOn();
// RefinedAbstraction
class AdvancedRemoteControl extends RemoteControl {
public AdvancedRemoteControl(Device device) {
super(device);
public void powerOn() {
device.turnOn();
// Implementor
interface Device {
void turnOn();
// ConcreteImplementor
class Television implements Device {
public void turnOn() {
System.out.println("Turning on the television.");
class Stereo implements Device {
public void turnOn() {
System.out.println("Turning on the stereo.");
2.3 Composite Pattern
Description: Allows individual objects and compositions of objects to be treated uniformly.
Real-World Example: A file system where both files and directories are treated as file system
objects.
import java.util.ArrayList;
import java.util.List;
// Component
interface FileSystemComponent {
void showDetails();
// Leaf
class File implements FileSystemComponent {
private String name;
public File(String name) {
this.name = name;
public void showDetails() {
System.out.println("File: " + name);
// Composite
class Directory implements FileSystemComponent {
private String name;
private List<FileSystemComponent> children = new ArrayList<>();
public Directory(String name) {
this.name = name;
public void add(FileSystemComponent component) {
children.add(component);
}
public void showDetails() {
System.out.println("Directory: " + name);
for (FileSystemComponent component : children) {
component.showDetails();
2.4 Decorator Pattern
Description: Adds new functionality to an object dynamically without altering its structure.
Real-World Example: Adding extra features to a coffee, such as milk or sugar, in a coffee shop.
// Component
interface Coffee {
String getDescription();
double cost();
// ConcreteComponent
class SimpleCoffee implements Coffee {
public String getDescription() {
return "Simple coffee";
public double cost() {
return 5.0;
}
}
// Decorator
abstract class CoffeeDecorator implements Coffee {
protected Coffee coffee;
public CoffeeDecorator(Coffee coffee) {
this.coffee = coffee;
public String getDescription() {
return coffee.getDescription();
public double cost() {
return coffee.cost();
// ConcreteDecorator
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) {
super(coffee);
public String getDescription() {
return coffee.getDescription() + ", milk";
}
public double cost() {
return coffee.cost() + 1.0;
3. Behavioral Patterns
3.1 Strategy Pattern
Description: Defines a family of algorithms, encapsulates each one, and makes them
interchangeable.
Real-World Example: A payment system that can switch between different payment methods
(e.g., credit card, PayPal).
Java Example:
// Strategy
interface PaymentStrategy {
void pay(int amount);
// ConcreteStrategy
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using credit card.");
// ConcreteStrategy
class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal.");
}
// Context
class PaymentContext {
private PaymentStrategy strategy;
public PaymentContext(PaymentStrategy strategy) {
this.strategy = strategy;
public void executePayment(int amount) {
strategy.pay(amount);
3.2 Observer Pattern
Description: Defines a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically.
Real-World Example: A news agency that notifies all subscribers when a new article is
published.
Java Example:
import java.util.ArrayList;
import java.util.List;
// Observer
interface Observer {
void update(String news);
}
// ConcreteObserver
class NewsSubscriber implements Observer {
private String name;
public NewsSubscriber(String name) {
this.name = name;
public void update(String news) {
System.out.println(name + " received news: " + news);
// Subject
class NewsAgency {
private List<Observer> observers = new ArrayList<>();
private String latestNews;
public void addObserver(Observer observer) {
observers.add(observer);
public void removeObserver(Observer observer) {
observers.remove(observer);
public void setNews(String news) {
this.latestNews = news;
notifyObservers();
private void notifyObservers() {
for (Observer observer : observers) {
observer.update(latestNews);
3.3 Command Pattern
Description: Encapsulates a request as an object, thereby allowing parameterization of clients
with queues, requests, and operations.
Real-World Example: A remote control that can execute different commands (e.g., turn on
lights, change TV channel).
Java Example:
// Command
interface Command {
void execute();
// ConcreteCommand
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.turnOn();
// Receiver
class Light {
public void turnOn() {
System.out.println("Light is on.");
// Invoker
class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
public void pressButton() {
command.execute();
3.4 State Pattern
Description: Allows an object to alter its behavior when its internal state changes.
Real-World Example: A document editor with states like "Editing," "Read-Only," and
"Locked."
Java Example:
// State
interface State {
void handleRequest();
// ConcreteState
class EditingState implements State {
public void handleRequest() {
System.out.println("Document is in editing state.");
// ConcreteState
class ReadOnlyState implements State {
public void handleRequest() {
System.out.println("Document is in read-only state.");
// Context
class Document {
private State state;
public void setState(State state) {
this.state = state;
public void request() {
state.handleRequest();
3.5 Template Method Pattern
Description: Defines the skeleton of an algorithm in the superclass but lets subclasses override
specific steps of the algorithm without changing its structure.
Real-World Example: A recipe with fixed steps where specific ingredients or cooking times can
be customized.
Java Example:
abstract class CoffeeTemplate {
public final void makeCoffee() {
boilWater();
brew();
pourInCup();
addCondiments();
protected abstract void brew();
protected abstract void addCondiments();
private void boilWater() {
System.out.println("Boiling water.");
}
private void pourInCup() {
System.out.println("Pouring coffee into cup.");
class Tea extends CoffeeTemplate {
protected void brew() {
System.out.println("Steeping the tea.");
protected void addCondiments() {
System.out.println("Adding lemon.");
class Coffee extends CoffeeTemplate {
protected void brew() {
System.out.println("Dripping coffee through filter.");
protected void addCondiments() {
System.out.println("Adding sugar and milk.");
3.6 Iterator Pattern
Description: Provides a way to access the elements of an aggregate object sequentially without
exposing its underlying representation.
Real-World Example: An iterator over a playlist of songs where you can move through each
song one by one.
Java Example:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// Aggregate
interface Aggregate {
Iterator<String> createIterator();
// ConcreteAggregate
class SongCollection implements Aggregate {
private List<String> songs = new ArrayList<>();
public void addSong(String song) {
songs.add(song);
public Iterator<String> createIterator() {
return songs.iterator();
3.7 Mediator Pattern
Description: Defines an object that encapsulates how a set of objects interact.
Real-World Example: A flight control tower managing interactions between multiple planes.
Java Example:
// Mediator
interface Mediator {
void sendMessage(String message, Colleague colleague);
// ConcreteMediator
class ConcreteMediator implements Mediator {
private ColleagueA colleagueA;
private ColleagueB colleagueB;
public void setColleagueA(ColleagueA colleagueA) {
this.colleagueA = colleagueA;
public void setColleagueB(ColleagueB colleagueB) {
this.colleagueB = colleagueB;
public void sendMessage(String message, Colleague colleague) {
if (colleague == colleagueA) {
colleagueB.receiveMessage(message);
} else {
colleagueA.receiveMessage(message);
// Colleague
abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
// ConcreteColleagueA
class ColleagueA extends Colleague {
public ColleagueA(Mediator mediator) {
super(mediator);
public void sendMessage(String message) {
mediator.sendMessage(message, this);
public void receiveMessage(String message) {
System.out.println("ColleagueA received: " + message);
// ConcreteColleagueB
class ColleagueB extends Colleague {
public ColleagueB(Mediator mediator) {
super(mediator);
public void receiveMessage(String message) {
System.out.println("ColleagueB received: " + message);
3.8 Chain of Responsibility Pattern
Description: Allows passing of requests along a chain of handlers.
Real-World Example: A help desk system where requests are passed from a junior support
agent to a senior one if the issue is not resolved.
Java Example:
abstract class Handler {
protected Handler nextHandler;
public void setNextHandler(Handler handler) {
this.nextHandler = handler;
public abstract void handleRequest(String request);
class ConcreteHandlerA extends Handler {
public void handleRequest(String request) {
if (request.equals("A")) {
System.out.println("Handler A processing request.");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
class ConcreteHandlerB extends Handler {
public void handleRequest(String request) {
if (request.equals("B")) {
System.out.println("Handler B processing request.");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
3.9 Visitor Pattern
Description: Allows adding new operations to objects without modifying the objects themselves.
Real-World Example: A tax calculation system that applies different tax rules to different types
of items (e.g., books, electronics).
Java Example:
// Visitor
interface Visitor {
void visit(Book book);
void visit(Electronic electronic);
// Element
interface Element {
void accept(Visitor visitor);
// ConcreteElement
class Book implements Element {
public void accept(Visitor visitor) {
visitor.visit(this);
// ConcreteElement
class Electronic implements Element {
public void accept(Visitor visitor) {
visitor.visit(this);
// ConcreteVisitor
class TaxVisitor implements Visitor {
public void visit(Book book) {
System.out.println("Tax for book: $5");
public void visit(Electronic electronic) {
System.out.println("Tax for electronic: $15");