OOP/Lesson 5 of 5/6 min read
Design Patterns
The Gang of Four creational, structural and behavioral patterns interviewers ask about most, with code and when to use each.
On this page
Design Pattern
A design pattern is a reusable solution to a common design problem in a given context. Catalogued by the "Gang of Four" (Gamma, Helm, Johnson, Vlissides) in 1994 as 23 patterns in three groups.
| Group | Concern | Examples |
|---|---|---|
| Creational | How objects are created | Singleton, Factory, Builder |
| Structural | How objects are composed | Adapter, Decorator, Facade, Proxy |
| Behavioral | How objects communicate | Strategy, Observer, Command |
Creational Pattern
Singleton
Ensures a class has exactly one instance and provides a global access point. Used for configuration, logging, connection pools.
public class Config {
private static volatile Config instance;
private Config() { } // no outside construction
public static Config get() {
if (instance == null) {
synchronized (Config.class) {
if (instance == null) instance = new Config(); // double-checked locking
}
}
return instance;
}
}volatile prevents another thread from seeing a half-constructed object. Simpler thread-safe options: eager initialization, the holder idiom, or an enum singleton (also safe against reflection and serialization).
Criticism: it is global state in disguise, hides dependencies and makes tests hard. Prefer dependency injection with a single shared instance.
Factory Method
Defines an interface for creating an object but lets subclasses or a method decide which class to instantiate. Callers depend on the product interface, not concrete classes.
interface Notification { void send(String msg); }
class NotificationFactory {
static Notification create(String channel) {
return switch (channel) {
case "email" -> new EmailNotification();
case "sms" -> new SmsNotification();
default -> throw new IllegalArgumentException(channel);
};
}
}Abstract Factory
A factory of families of related objects. A GuiFactory interface with WindowsFactory and MacFactory, each producing matching Button and Checkbox objects, guaranteeing they are consistent.
Builder Pattern
Constructs complex objects step by step; avoids telescoping constructors with many optional parameters.
Pizza p = new Pizza.Builder("large")
.cheese(true)
.pepperoni(true)
.build(); // validates and returns an immutable PizzaUsed by StringBuilder, HTTP request builders, Lombok @Builder.
Prototype Pattern
Create new objects by cloning an existing instance instead of constructing from scratch. Useful when construction is expensive. Beware shallow vs deep copy.
Structural Pattern
Adapter Pattern
Converts one interface into another that clients expect. Lets incompatible classes work together, like a travel plug adapter.
interface PaymentProcessor { void pay(double amount); }
class LegacyGateway { void makePayment(int cents) { ... } }
class LegacyAdapter implements PaymentProcessor {
private final LegacyGateway legacy;
LegacyAdapter(LegacyGateway l) { this.legacy = l; }
public void pay(double amount) { legacy.makePayment((int) (amount * 100)); }
}Decorator Pattern
Adds behavior to an object dynamically by wrapping it in objects with the same interface. A flexible alternative to subclassing for every combination.
InputStream in = new BufferedInputStream(new GZIPInputStream(new FileInputStream("a.gz")));Each wrapper adds one feature (buffering, decompression). Python's @decorator syntax is a related idea for functions.
Facade Pattern
Provides a simple unified interface to a complex subsystem. VideoConverter.convert(file, "mp4") hides codecs, buffers and audio mixing.
Proxy Pattern
A stand-in object that controls access to another object with the same interface.
| Proxy type | Purpose |
|---|---|
| Virtual | Lazy-load an expensive object |
| Protection | Check permissions before forwarding |
| Remote | Represent an object in another process (RPC stubs) |
| Caching | Return cached results |
Adapter changes the interface; decorator keeps it and adds behavior; proxy keeps it and controls access; facade simplifies a whole subsystem.
Behavioral Pattern
Strategy Pattern
Defines a family of interchangeable algorithms, each in its own class, selected at runtime. Replaces big if/else chains.
interface SortStrategy { void sort(int[] a); }
class Sorter {
private SortStrategy strategy;
void setStrategy(SortStrategy s) { strategy = s; }
void sort(int[] a) { strategy.sort(a); }
}Examples: payment methods, compression algorithms, Comparator in Java.
Observer Pattern
A subject maintains a list of observers and notifies them of state changes. One-to-many, loosely coupled. Also called publish-subscribe (pub-sub at a larger scale uses a broker).
interface Observer { void update(String event); }
class Subject {
private final List<Observer> observers = new ArrayList<>();
void subscribe(Observer o) { observers.add(o); }
void publish(String e) { for (Observer o : observers) o.update(e); }
}Used in UI event listeners, React state updates, stock tickers, notification systems. Pitfall: forgetting to unsubscribe causes memory leaks.
Command Pattern
Encapsulates a request as an object with execute() (and often undo()). Enables undo/redo stacks, queuing, logging and macro recording.
Template Method
Base class defines the skeleton of an algorithm in a final method; subclasses fill in specific steps. Example: a DataExporter with fixed export() that calls abstract fetch(), format(), write().
State Pattern
An object changes behavior when its internal state changes, by delegating to a state object. A vending machine with Idle, HasCoin, Dispensing states, each handling insertCoin() differently. Removes giant switch(state) blocks.
Other behavioral patterns worth knowing: Iterator (traverse without exposing structure), Chain of Responsibility (middleware pipelines), Mediator, Visitor.
MVC
Model-View-Controller is an architectural pattern that separates concerns in UI applications:
- Model: data and business logic.
- View: presentation.
- Controller: handles input, updates the model, picks the view.
Variants: MVP, MVVM (data binding in Angular, SwiftUI). Built internally on Observer (model notifies view), Strategy (controller is the view's strategy) and Composite (nested views).
Choosing a pattern
| Problem | Pattern |
|---|---|
| Exactly one shared instance | Singleton (or DI) |
| Many optional constructor params | Builder |
| Create objects without naming concrete classes | Factory Method |
| Make an incompatible class fit | Adapter |
| Add features in combinations at runtime | Decorator |
| Swap algorithms at runtime | Strategy |
| Notify many listeners of changes | Observer |
| Undo and redo | Command |
| Behavior depends on internal state | State |
| Lazy loading or access control | Proxy |
Quick revision
- Creational: Singleton (one instance, thread-safe init), Factory (hide concrete class), Builder (step-by-step, optional params).
- Structural: Adapter (convert interface), Decorator (wrap to add behavior), Facade (simplify subsystem), Proxy (control access).
- Behavioral: Strategy (swap algorithms), Observer (notify subscribers), Command (requests as objects, undo), State (behavior by state).
- Singleton criticism: hidden global state; prefer dependency injection.
- MVC separates model, view and controller, and is built on Observer and Strategy.