Design patterns refresher
Design patterns are reusable solutions to common design problems. The Gang of Four book (1994) catalogued 23; modern practice uses a subset frequently. Below are the ones you'll meet in LLD interviews.
Creational patterns — how objects come into being
When to use: when there's a genuine single-shared resource and global access is acceptable.
When to avoid: anywhere you might want to swap implementations (testing, multi-tenancy, etc.).
When to use: when the choice of concrete class depends on runtime state (e.g., VehicleFactory creating Car/Motorcycle/Truck based on input).
classDiagram
direction LR
class VehicleFactory {
+create()
}
class Vehicle
class Car
class Motorcycle
class Truck
VehicleFactory --> Vehicle
Car ..|> Vehicle
Motorcycle ..|> Vehicle
Truck ..|> Vehicle
Java example: Pizza.builder().withSize("Large").withTopping("Cheese").withTopping("Mushrooms").build().
Structural patterns — how objects compose
File and Directory both implement FileSystemNode; Directory contains a list of nodes (which may be Files or other Directories).
Behavioral patterns — how objects communicate
Canonical use: PaymentMethod interface with implementations CardPayment, UpiPayment, etc. Caller passes the desired strategy; behavior varies per call.
classDiagram
direction LR
class Context {
+setStrategy()
+execute()
}
class Strategy {
+execute()
}
class CardPayment
class UpiPayment
class WalletPayment
Context o-- Strategy
CardPayment ..|> Strategy
UpiPayment ..|> Strategy
WalletPayment ..|> Strategy
Canonical use: news feed, event systems, UI updates.
classDiagram
direction LR
class Subject {
+attach()
+detach()
+notify()
}
class Observer {
+update()
}
class EmailNotifier
class PushNotifier
class AuditLogger
Subject o-- Observer
EmailNotifier ..|> Observer
PushNotifier ..|> Observer
AuditLogger ..|> Observer
When to use which pattern (the meta-skill)
Most patterns address a specific recurring problem:
| Problem | Pattern |
|---|---|
| Algorithm should be swappable at runtime | Strategy |
| Object's behavior depends on its state | State |
| One object's change needs to update many | Observer |
| Construction is complex, many fields, immutability desired | Builder |
| Need a single instance globally | Singleton (carefully) |
| Concrete class depends on runtime data | Factory |
| Tree structure with uniform handling | Composite |
| Add behaviors dynamically | Decorator |
| Multiple handlers, sequential filtering | Chain of Responsibility |
| Encapsulate an action; support undo | Command |