Java Design Patterns
Java Design Patterns
1. Singleton Pattern
Concept:
● Ensures that a class has only one instance and provides a global point of access
to it.
● Used when only one object should control the entire application's behavior (e.g.,
logging, database connection, configuration manager).
Implementation:
class Singleton {
private static final Singleton instance = new Singleton(); //
Instance created eagerly
private Singleton() {} // Private constructor prevents
instantiation
public static Singleton getInstance() {
return instance;
}
}
class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton(); // Creates instance only
when needed
}
return instance;
}
}
Thread-safe Singleton (Double-Checked Locking)
java
class Singleton {
private static volatile Singleton instance;
private Singleton() {}
enum Singleton {
INSTANCE;
Interview Questions:
● Used to create objects without exposing the creation logic to the client.
● Helps in handling object creation based on conditions.
Implementation:
java
// Step 4: Usage
public class FactoryPatternDemo {
public static void main(String[] args) {
Shape shape1 = ShapeFactory.getShape("CIRCLE");
shape1.draw();
Interview Questions:
3. Builder Pattern
Concept:
Implementation:
java
class Computer {
// Required parameters
private String CPU;
private int RAM;
// Optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
// Usage
public class BuilderPatternDemo {
public static void main(String[] args) {
Computer computer = new Computer.ComputerBuilder("Intel i7",
16)
.setGraphicsCardEnabled(true)
.setBluetoothEnabled(false)
.build();
}
}
Interview Questions:
4. Prototype Pattern
Concept:
Implementation:
java
@Override
protected Prototype clone() throws CloneNotSupportedException {
return (Prototype) super.clone();
}
}
System.out.println(p1.name);
System.out.println(p2.name);
}
}
Interview Questions:
5. Observer Pattern
Concept:
● Used when one object (Subject) needs to notify multiple dependent objects
(Observers) about state changes.
Implementation:
java
import java.util.ArrayList;
import java.util.List;
// Observer interface
interface Observer {
void update(String message);
}
// Concrete Observer
class User implements Observer {
private String name;
@Override
public void update(String message) {
System.out.println(name + " received message: " + message);
}
}
// Subject class
class Channel {
private List<Observer> observers = new ArrayList<>();
public void subscribe(Observer observer) {
observers.add(observer);
}
// Usage
public class ObserverPatternDemo {
public static void main(String[] args) {
Channel channel = new Channel();
channel.subscribe(user1);
channel.subscribe(user2);
Interview Questions:
6. Decorator Pattern
Concept:
Use Case:
● When we want to extend functionality of classes without altering their structure.
● Example: Adding extra features to coffee (like sugar, milk) without modifying the
base Coffee class.
Implementation:
java
// Step 5: Usage
public class DecoratorPatternDemo {
public static void main(String[] args) {
Coffee coffee = new SimpleCoffee();
System.out.println(coffee.getDescription() + " = Rs." +
coffee.cost());
Output:
java
Interview Questions:
7. Adapter Pattern
Concept:
● Converts one interface into another so that two incompatible interfaces can work
together.
● Acts as a bridge between two classes.
Use Case:
Implementation:
java
// Step 4: Usage
public class AdapterPatternDemo {
public static void main(String[] args) {
OldCharger oldCharger = new OldCharger();
NewCharger newCharger = new ChargerAdapter(oldCharger);
newCharger.chargeWithFlatPin();
}
}
Output:
Singleton Ensures one instance of a When a single control point is needed (e.g.,
class database connection, logging)
Observer Notifies dependent objects When multiple objects should react to one
about state changes object's changes (e.g., event listeners)