# Design Patterns: Concepts, Use Cases, and Implementations
A practical guide to the 23 Gang of Four (GoF) design patterns, with implementation examples in TypeScript (JavaScript/NestJS-friendly) and Python. The examples are intentionally small so the underlying pattern is easy
A practical guide to the 23 Gang of Four (GoF) design patterns, with
implementation examples in TypeScript (JavaScript/NestJS-friendly)
and Python.
The examples are intentionally small so the underlying pattern is easy
to see. In a real application, add validation, error handling,
logging, dependency injection, and tests as appropriate.
Contents
- 1. What is a design pattern?
- 2. How to choose a pattern
- 3. Creational patterns
- 1. Singleton
- 2. Factory Method
- 3. Abstract Factory
- 4. Builder
- 5. Prototype
- 4. Structural patterns
- 6. Adapter
- 7. Bridge
- 8. Composite
- 9. Decorator
- 10. Facade
- 11. Flyweight
- 12. Proxy
- 5. Behavioral patterns
- 13. Chain of Responsibility
- 14. Command
- 15. Interpreter
- 16. Iterator
- 17. Mediator
- 18. Memento
- 19. Observer
- 20. State
- 21. Strategy
- 22. Template Method
- 23. Visitor
- 6. Common application and architecture patterns
- 7. Patterns in a layered backend
- 8. Testing checklist
- 9. Quick revision table
1. What is a design pattern?
A design pattern is a reusable way to solve a recurring
software-design problem. It is not a complete application or a library
to copy blindly. It describes a structure: which objects or classes
participate, how they collaborate, and which design trade-offs are
involved.
Why use them?
- Reduce tight coupling between components.
- Make code easier to extend and test.
- Give developers a shared vocabulary.
- Prefer composition and clear responsibilities over large conditional blocks or inheritance trees.
Important distinction
A pattern is not automatically better than a simple implementation. Use
one when it makes the design clearer. Avoid adding abstractions for a
problem that does not exist.
2. How to choose a pattern
Problem Patterns worth considering
Object creation varies Factory Method, Abstract Factory, Builder
Need one shared instance Singleton
Need to adapt an incompatible API Adapter
Need to add behavior without changing a class Decorator
Need a simple entry point to a complex subsystem Facade
Need access control, lazy loading, or caching Proxy
Need interchangeable algorithms Strategy
One object must notify many dependents Observer
A request should pass through handlers Chain of Responsibility
Need to represent an operation as an object Command
Behavior changes with an object's state State
Need to traverse a collection uniformly Iterator
3. Creational patterns
Creational patterns focus on how objects are created.
1. Singleton
Intent: Ensure a class has one shared instance and provide a common
access point.
Use when: A process-wide configuration object or a resource
coordinator genuinely needs one instance. For database connections,
prefer a connection pool managed by the application framework rather
than creating an ad-hoc singleton.
TypeScript
class AppConfig {
private static instance: AppConfig;
private constructor(public readonly environment = "development") {}
static getInstance(): AppConfig {
if (!AppConfig.instance) AppConfig.instance = new AppConfig();
return AppConfig.instance;
}
}
const a = AppConfig.getInstance();
const b = AppConfig.getInstance();
console.log(a === b); // true
Python
class AppConfig:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.environment = "development"
return cls._instance
a = AppConfig()
b = AppConfig()
print(a is b) # True
Trade-offs: Hidden global state can make tests order-dependent. In
concurrent or multi-process applications, clarify what "one instance"
means. Dependency injection is often a cleaner way to share a service.
2. Factory Method
Intent: Define a creation method while allowing subclasses to decide
which concrete product is created.
Use when: A workflow uses a common interface, but the concrete
implementation depends on configuration or the environment.
TypeScript
interface Notifier {
send(message: string): void;
}
class EmailNotifier implements Notifier {
send(message: string) { console.log("Email:", message); }
}
class SmsNotifier implements Notifier {
send(message: string) { console.log("SMS:", message); }
}
abstract class NotificationService {
protected abstract createNotifier(): Notifier;
notify(message: string) {
this.createNotifier().send(message);
}
}
class EmailService extends NotificationService {
protected createNotifier() { return new EmailNotifier(); }
}
class SmsService extends NotificationService {
protected createNotifier() { return new SmsNotifier(); }
}
new EmailService().notify("Welcome");
Python
from abc import ABC, abstractmethod
class Notifier(ABC):
@abstractmethod
def send(self, message: str) -> None: ...
class EmailNotifier(Notifier):
def send(self, message): print("Email:", message)
class SmsNotifier(Notifier):
def send(self, message): print("SMS:", message)
class NotificationService(ABC):
@abstractmethod
def create_notifier(self) -> Notifier: ...
def notify(self, message):
self.create_notifier().send(message)
class EmailService(NotificationService):
def create_notifier(self): return EmailNotifier()
EmailService().notify("Welcome")
Note: A simple function that returns an object is often called a
simple factory. The GoF Factory Method specifically relies on a
creation method that subclasses can override.
3. Abstract Factory
Intent: Create families of related objects without specifying their
concrete classes.
Use when: The application supports multiple product families, such
as light/dark UI components or cloud-provider-specific storage and
queues.
TypeScript
interface Button { render(): string; }
interface Checkbox { render(): string; }
class LightButton implements Button { render() { return "Light button"; } }
class LightCheckbox implements Checkbox { render() { return "Light checkbox"; } }
class DarkButton implements Button { render() { return "Dark button"; } }
class DarkCheckbox implements Checkbox { render() { return "Dark checkbox"; } }
interface UIFactory {
createButton(): Button;
createCheckbox(): Checkbox;
}
class LightFactory implements UIFactory {
createButton() { return new LightButton(); }
createCheckbox() { return new LightCheckbox(); }
}
class DarkFactory implements UIFactory {
createButton() { return new DarkButton(); }
createCheckbox() { return new DarkCheckbox(); }
}
function buildScreen(factory: UIFactory) {
return [factory.createButton().render(), factory.createCheckbox().render()];
}
console.log(buildScreen(new DarkFactory()));
Python
from abc import ABC, abstractmethod
class UIFactory(ABC):
@abstractmethod
def create_button(self): ...
@abstractmethod
def create_checkbox(self): ...
class LightFactory(UIFactory):
def create_button(self): return "Light button"
def create_checkbox(self): return "Light checkbox"
class DarkFactory(UIFactory):
def create_button(self): return "Dark button"
def create_checkbox(self): return "Dark checkbox"
def build_screen(factory: UIFactory):
return [factory.create_button(), factory.create_checkbox()]
print(build_screen(DarkFactory()))
Factory Method vs Abstract Factory: Factory Method usually creates
one product through an overridable method. Abstract Factory exposes
several creation methods for a related family of products.
4. Builder
Intent: Construct a complex object step by step, separating
construction from the final representation.
Use when: An object has many optional settings or must be assembled
in a controlled sequence.
TypeScript
type UserOptions = { name: string; email?: string; admin?: boolean };
class UserBuilder {
private options: UserOptions;
constructor(name: string) { this.options = { name }; }
withEmail(email: string) { this.options.email = email; return this; }
asAdmin() { this.options.admin = true; return this; }
build(): Readonly<UserOptions> { return Object.freeze({ ...this.options }); }
}
const user = new UserBuilder("Maya")
.withEmail("[email protected]")
.asAdmin()
.build();
Python
from dataclasses import dataclass
@dataclass(frozen=True)
class User:
name: str
email: str | None = None
admin: bool = False
class UserBuilder:
def __init__(self, name):
self._name, self._email, self._admin = name, None, False
def with_email(self, email):
self._email = email
return self
def as_admin(self):
self._admin = True
return self
def build(self):
return User(self._name, self._email, self._admin)
user = UserBuilder("Maya").with_email("[email protected]").as_admin().build()
Trade-off: For a small object, a constructor with named options or a
dataclass may be simpler.
5. Prototype
Intent: Create a new object by copying an existing prototype.
Use when: A preconfigured object is expensive or cumbersome to
construct repeatedly.
TypeScript
class DocumentTemplate {
constructor(
public title: string,
public metadata: { tags: string[] }
) {}
clone(): DocumentTemplate {
return new DocumentTemplate(this.title, {
tags: [...this.metadata.tags]
});
}
}
const original = new DocumentTemplate("Report", { tags: ["draft"] });
const copy = original.clone();
copy.metadata.tags.push("review");
Python
from copy import deepcopy
class DocumentTemplate:
def __init__(self, title, metadata):
self.title = title
self.metadata = metadata
original = DocumentTemplate("Report", {"tags": ["draft"]})
copy = deepcopy(original)
copy.metadata["tags"].append("review")
Shallow vs deep copy: A shallow copy duplicates the outer object but
shares nested references. A deep copy recursively copies nested objects.
Choose deliberately.
4. Structural patterns
Structural patterns focus on how classes and objects are composed.
6. Adapter
Intent: Convert one interface into another interface expected by the
client.
Use when: Integrating a third-party library or legacy class whose
method names or data format do not match your application's interface.
TypeScript
interface PaymentGateway {
pay(amountInPaise: number): void;
}
// Third-party API: incompatible method and unit.
class LegacyGateway {
makePayment(amountInRupees: number) {
console.log("Paid βΉ", amountInRupees);
}
}
class GatewayAdapter implements PaymentGateway {
constructor(private legacy: LegacyGateway) {}
pay(amountInPaise: number) {
this.legacy.makePayment(amountInPaise / 100);
}
}
const gateway: PaymentGateway = new GatewayAdapter(new LegacyGateway());
gateway.pay(12500);
Python
from abc import ABC, abstractmethod
class PaymentGateway(ABC):
@abstractmethod
def pay(self, amount_in_paise: int): ...
class LegacyGateway:
def make_payment(self, amount_in_rupees):
print("Paid βΉ", amount_in_rupees)
class GatewayAdapter(PaymentGateway):
def __init__(self, legacy):
self.legacy = legacy
def pay(self, amount_in_paise):
self.legacy.make_payment(amount_in_paise / 100)
GatewayAdapter(LegacyGateway()).pay(12500)
Key idea: The adapter implements the interface the client expects
and delegates to the incompatible class after translating the call or
data.
7. Bridge
Intent: Separate an abstraction from its implementation so both can
vary independently.
Use when: Two dimensions vary independently, such as notification
type and delivery channel.
TypeScript
interface Sender { send(message: string): void; }
class EmailSender implements Sender {
send(message: string) { console.log("Email:", message); }
}
class SmsSender implements Sender {
send(message: string) { console.log("SMS:", message); }
}
abstract class Alert {
constructor(protected sender: Sender) {}
abstract notify(message: string): void;
}
class UrgentAlert extends Alert {
notify(message: string) { this.sender.send("URGENT: " + message); }
}
class NormalAlert extends Alert {
notify(message: string) { this.sender.send(message); }
}
new UrgentAlert(new SmsSender()).notify("Server down");
Python
class EmailSender:
def send(self, message): print("Email:", message)
class SmsSender:
def send(self, message): print("SMS:", message)
class Alert:
def __init__(self, sender): self.sender = sender
class UrgentAlert(Alert):
def notify(self, message): self.sender.send("URGENT: " + message)
class NormalAlert(Alert):
def notify(self, message): self.sender.send(message)
UrgentAlert(SmsSender()).notify("Server down")
Adapter vs Bridge: Adapter makes an existing incompatible interface
usable. Bridge is designed up front to separate two independently
varying dimensions.
8. Composite
Intent: Compose objects into tree structures and treat individual
objects and groups uniformly.
Use when: Representing file systems, UI component trees, or
organizational hierarchies.
TypeScript
interface FileSystemItem {
getSize(): number;
}
class File implements FileSystemItem {
constructor(private size: number) {}
getSize() { return this.size; }
}
class Folder implements FileSystemItem {
private children: FileSystemItem[] = [];
add(item: FileSystemItem) { this.children.push(item); }
getSize() { return this.children.reduce((sum, item) => sum + item.getSize(), 0); }
}
const root = new Folder();
root.add(new File(10));
const nested = new Folder();
nested.add(new File(20));
root.add(nested);
console.log(root.getSize()); // 30
Python
from abc import ABC, abstractmethod
class FileSystemItem(ABC):
@abstractmethod
def get_size(self): ...
class File(FileSystemItem):
def __init__(self, size): self.size = size
def get_size(self): return self.size
class Folder(FileSystemItem):
def __init__(self): self.children = []
def add(self, item): self.children.append(item)
def get_size(self): return sum(item.get_size() for item in self.children)
root = Folder()
root.add(File(10))
nested = Folder()
nested.add(File(20))
root.add(nested)
print(root.get_size()) # 30
9. Decorator
Intent: Attach additional behavior to an object dynamically by
wrapping it, without changing the original class.
Use when: Adding logging, caching, validation, compression, or
authorization around a service.
TypeScript
interface DataService { getData(): string; }
class ApiService implements DataService {
getData() { return "data from API"; }
}
class LoggingDecorator implements DataService {
constructor(private inner: DataService) {}
getData() {
console.log("getData called");
return this.inner.getData();
}
}
const service: DataService = new LoggingDecorator(new ApiService());
console.log(service.getData());
Python
class ApiService:
def get_data(self):
return "data from API"
class LoggingDecorator:
def __init__(self, inner):
self.inner = inner
def get_data(self):
print("get_data called")
return self.inner.get_data()
service = LoggingDecorator(ApiService())
print(service.get_data())
Decorator vs Adapter: Decorator preserves the interface and adds
behavior. Adapter changes/translates the interface. Multiple decorators
can be stacked.
10. Facade
Intent: Provide a simple, unified interface to a complex subsystem.
Use when: A use case requires several subsystem operations and
callers should not coordinate them directly.
TypeScript
class Inventory {
reserve(productId: string) { console.log("Reserved", productId); }
}
class Payment {
charge(amount: number) { console.log("Charged", amount); }
}
class Shipping {
dispatch(productId: string) { console.log("Dispatched", productId); }
}
class OrderFacade {
constructor(
private inventory: Inventory,
private payment: Payment,
private shipping: Shipping
) {}
placeOrder(productId: string, amount: number) {
this.inventory.reserve(productId);
this.payment.charge(amount);
this.shipping.dispatch(productId);
}
}
new OrderFacade(new Inventory(), new Payment(), new Shipping())
.placeOrder("P-10", 500);
Python
class Inventory:
def reserve(self, product_id): print("Reserved", product_id)
class Payment:
def charge(self, amount): print("Charged", amount)
class Shipping:
def dispatch(self, product_id): print("Dispatched", product_id)
class OrderFacade:
def __init__(self, inventory, payment, shipping):
self.inventory, self.payment, self.shipping = inventory, payment, shipping
def place_order(self, product_id, amount):
self.inventory.reserve(product_id)
self.payment.charge(amount)
self.shipping.dispatch(product_id)
OrderFacade(Inventory(), Payment(), Shipping()).place_order("P-10", 500)
Important: A facade simplifies access; it does not necessarily
replace the subsystem or enforce all business rules. Real order
placement also needs transaction/compensation handling.
11. Flyweight
Intent: Share common, immutable state across many objects to reduce
memory use.
Use when: A very large number of objects repeat the same intrinsic
data, such as character formatting or map icons.
TypeScript
class TreeType {
constructor(
public readonly name: string,
public readonly color: string
) {}
}
class TreeTypeFactory {
private static cache = new Map<string, TreeType>();
static get(name: string, color: string): TreeType {
const key = `${name}:${color}`;
if (!this.cache.has(key)) this.cache.set(key, new TreeType(name, color));
return this.cache.get(key)!;
}
}
class Tree {
constructor(
public x: number, public y: number,
public type: TreeType // shared intrinsic state
) {}
}
const t1 = new Tree(1, 2, TreeTypeFactory.get("Oak", "Green"));
const t2 = new Tree(5, 8, TreeTypeFactory.get("Oak", "Green"));
console.log(t1.type === t2.type); // true
Python
class TreeType:
def __init__(self, name, color):
self.name, self.color = name, color
class TreeTypeFactory:
_cache = {}
@classmethod
def get(cls, name, color):
key = (name, color)
if key not in cls._cache:
cls._cache[key] = TreeType(name, color)
return cls._cache[key]
class Tree:
def __init__(self, x, y, tree_type):
self.x, self.y, self.type = x, y, tree_type
t1 = Tree(1, 2, TreeTypeFactory.get("Oak", "Green"))
t2 = Tree(5, 8, TreeTypeFactory.get("Oak", "Green"))
print(t1.type is t2.type) # True
Intrinsic vs extrinsic state: Intrinsic state is shared (tree
species and color); extrinsic state is supplied per use (tree position).
Shared state should generally be immutable.
12. Proxy
Intent: Provide a substitute object that controls access to another
object.
Use when: Lazy loading, access control, caching, rate limiting, or
remote access.
TypeScript
interface Report { load(): string; }
class RealReport implements Report {
load() {
console.log("Expensive report loaded");
return "Annual report";
}
}
class ReportProxy implements Report {
private real?: RealReport;
constructor(private allowed: boolean) {}
load() {
if (!this.allowed) throw new Error("Access denied");
this.real ??= new RealReport(); // lazy creation
return this.real.load();
}
}
console.log(new ReportProxy(true).load());
Python
class RealReport:
def load(self):
print("Expensive report loaded")
return "Annual report"
class ReportProxy:
def __init__(self, allowed):
self.allowed = allowed
self._real = None
def load(self):
if not self.allowed:
raise PermissionError("Access denied")
if self._real is None:
self._real = RealReport()
return self._real.load()
print(ReportProxy(True).load())
Decorator vs Proxy: Both wrap another object. Decorator's main
purpose is adding responsibilities; Proxy's main purpose is controlling
access to the subject.
5. Behavioral patterns
Behavioral patterns focus on communication and responsibility between
objects.
13. Chain of Responsibility
Intent: Pass a request along a chain of handlers until one handles
it or the chain ends.
Use when: Middleware, validation pipelines, approval workflows, or
support escalation.
TypeScript
abstract class Handler {
private next?: Handler;
setNext(handler: Handler) { this.next = handler; return handler; }
handle(amount: number): string | undefined {
return this.next?.handle(amount);
}
}
class Manager extends Handler {
handle(amount: number) {
if (amount <= 1000) return "Approved by manager";
return super.handle(amount);
}
}
class Director extends Handler {
handle(amount: number) {
if (amount <= 10000) return "Approved by director";
return "Requires executive approval";
}
}
const manager = new Manager();
manager.setNext(new Director());
console.log(manager.handle(5000));
Python
class Handler:
def __init__(self): self.next = None
def set_next(self, handler):
self.next = handler
return handler
def handle(self, amount):
if self.next:
return self.next.handle(amount)
return None
class Manager(Handler):
def handle(self, amount):
if amount <= 1000: return "Approved by manager"
return super().handle(amount)
class Director(Handler):
def handle(self, amount):
if amount <= 10000: return "Approved by director"
return "Requires executive approval"
manager = Manager()
manager.set_next(Director())
print(manager.handle(5000))
14. Command
Intent: Encapsulate a request as an object, allowing it to be
queued, logged, retried, or undone.
Use when: Job queues, task scheduling, undo/redo, and menu actions.
TypeScript
interface Command { execute(): void; }
class Light {
on() { console.log("Light on"); }
off() { console.log("Light off"); }
}
class TurnOnCommand implements Command {
constructor(private light: Light) {}
execute() { this.light.on(); }
}
class RemoteControl {
submit(command: Command) { command.execute(); }
}
const light = new Light();
new RemoteControl().submit(new TurnOnCommand(light));
Python
class Light:
def on(self): print("Light on")
def off(self): print("Light off")
class TurnOnCommand:
def __init__(self, light): self.light = light
def execute(self): self.light.on()
class RemoteControl:
def submit(self, command): command.execute()
light = Light()
RemoteControl().submit(TurnOnCommand(light))
Undo: Add an undo() method to the command and retain executed
commands in history. Each command must know how to reverse its own
operation.
15. Interpreter
Intent: Represent a small language's grammar and interpret sentences
in that language.
Use when: Small rule languages, filters, or arithmetic expressions.
For complex languages, use a parser library rather than building a large
class hierarchy manually.
TypeScript
interface Expression { interpret(context: Record<string, number>): number; }
class NumberExpr implements Expression {
constructor(private value: number) {}
interpret() { return this.value; }
}
class VariableExpr implements Expression {
constructor(private name: string) {}
interpret(context: Record<string, number>) { return context[this.name] ?? 0; }
}
class AddExpr implements Expression {
constructor(private left: Expression, private right: Expression) {}
interpret(context: Record<string, number>) {
return this.left.interpret(context) + this.right.interpret(context);
}
}
const expr = new AddExpr(new VariableExpr("x"), new NumberExpr(5));
console.log(expr.interpret({ x: 7 })); // 12
Python
class NumberExpr:
def __init__(self, value): self.value = value
def interpret(self, context): return self.value
class VariableExpr:
def __init__(self, name): self.name = name
def interpret(self, context): return context.get(self.name, 0)
class AddExpr:
def __init__(self, left, right): self.left, self.right = left, right
def interpret(self, context):
return self.left.interpret(context) + self.right.interpret(context)
expr = AddExpr(VariableExpr("x"), NumberExpr(5))
print(expr.interpret({"x": 7})) # 12
16. Iterator
Intent: Access elements of a collection sequentially without
exposing its internal representation.
Use when: A collection needs a consistent traversal API or custom
iteration behavior.
TypeScript
class NumberCollection implements Iterable<number> {
constructor(private values: number[]) {}
[Symbol.iterator](): Iterator<number> {
let index = 0;
const values = this.values;
return {
next(): IteratorResult<number> {
if (index < values.length) {
return { value: values[index++], done: false };
}
return { value: undefined, done: true };
}
};
}
}
for (const value of new NumberCollection([10, 20, 30])) {
console.log(value);
}
Python
class NumberCollection:
def __init__(self, values):
self.values = values
def __iter__(self):
for value in self.values:
yield value
for value in NumberCollection([10, 20, 30]):
print(value)
Note: Native arrays, lists, generators, and language iteration
protocols already provide iterators. Implement a custom one only when
useful.
17. Mediator
Intent: Centralize complex communication between related objects so
they do not depend on each other directly.
Use when: Chat rooms, UI dialogs, or workflows where many components
interact.
TypeScript
interface ChatMediator { send(message: string, sender: User): void; }
class User {
constructor(private name: string, private mediator: ChatMediator) {}
send(message: string) { this.mediator.send(message, this); }
receive(message: string) { console.log(`${this.name} received: ${message}`); }
}
class ChatRoom implements ChatMediator {
private users: User[] = [];
add(user: User) { this.users.push(user); }
send(message: string, sender: User) {
for (const user of this.users) if (user !== sender) user.receive(message);
}
}
const room = new ChatRoom();
const a = new User("A", room), b = new User("B", room);
room.add(a); room.add(b);
a.send("Hello");
Python
class User:
def __init__(self, name, mediator):
self.name, self.mediator = name, mediator
def send(self, message): self.mediator.send(message, self)
def receive(self, message): print(f"{self.name} received: {message}")
class ChatRoom:
def __init__(self): self.users = []
def add(self, user): self.users.append(user)
def send(self, message, sender):
for user in self.users:
if user is not sender:
user.receive(message)
room = ChatRoom()
a, b = User("A", room), User("B", room)
room.add(a); room.add(b)
a.send("Hello")
Mediator vs Observer: Mediator coordinates interactions and often
contains workflow rules. Observer broadcasts that an event occurred to
registered listeners.
18. Memento
Intent: Capture and restore an object's previous state without
exposing its internal details.
Use when: Undo functionality, editor history, or snapshots.
TypeScript
class EditorMemento {
constructor(public readonly text: string) {}
}
class Editor {
private text = "";
write(text: string) { this.text = text; }
save() { return new EditorMemento(this.text); }
restore(snapshot: EditorMemento) { this.text = snapshot.text; }
getText() { return this.text; }
}
const editor = new Editor();
editor.write("Version 1");
const snapshot = editor.save();
editor.write("Version 2");
editor.restore(snapshot);
console.log(editor.getText()); // Version 1
Python
from dataclasses import dataclass
@dataclass(frozen=True)
class EditorMemento:
text: str
class Editor:
def __init__(self): self._text = ""
def write(self, text): self._text = text
def save(self): return EditorMemento(self._text)
def restore(self, snapshot): self._text = snapshot.text
def get_text(self): return self._text
editor = Editor()
editor.write("Version 1")
snapshot = editor.save()
editor.write("Version 2")
editor.restore(snapshot)
print(editor.get_text()) # Version 1
19. Observer
Intent: Define a one-to-many dependency so subscribers are notified
when a subject changes or emits an event.
Use when: Event notifications, UI updates, domain events, or pub/sub
systems.
TypeScript
type Listener = (temperature: number) => void;
class WeatherStation {
private listeners = new Set<Listener>();
subscribe(listener: Listener) { this.listeners.add(listener); }
unsubscribe(listener: Listener) { this.listeners.delete(listener); }
setTemperature(value: number) {
for (const listener of this.listeners) listener(value);
}
}
const station = new WeatherStation();
const display = (t: number) => console.log("Temperature:", t);
station.subscribe(display);
station.setTemperature(28);
station.unsubscribe(display);
Python
class WeatherStation:
def __init__(self): self.listeners = set()
def subscribe(self, listener): self.listeners.add(listener)
def unsubscribe(self, listener): self.listeners.discard(listener)
def set_temperature(self, value):
for listener in list(self.listeners):
listener(value)
station = WeatherStation()
def display(value): print("Temperature:", value)
station.subscribe(display)
station.set_temperature(28)
station.unsubscribe(display)
Practical concerns: Unsubscribe listeners when they are no longer
needed, avoid memory leaks, and decide how subscriber errors are
handled. For distributed systems, use a message broker rather than an
in-memory observer list.
20. State
Intent: Allow an object to change its behavior when its internal
state changes, making it appear as if its class changed.
Use when: Orders, payments, media players, or workflows with
state-dependent transitions.
TypeScript
interface OrderState {
pay(order: Order): void;
ship(order: Order): void;
}
class Pending implements OrderState {
pay(order: Order) { order.setState(new Paid()); }
ship(order: Order) { throw new Error("Pay before shipping"); }
}
class Paid implements OrderState {
pay(order: Order) { throw new Error("Already paid"); }
ship(order: Order) { order.setState(new Shipped()); }
}
class Shipped implements OrderState {
pay(order: Order) { throw new Error("Already shipped"); }
ship(order: Order) { throw new Error("Already shipped"); }
}
class Order {
private state: OrderState = new Pending();
setState(state: OrderState) { this.state = state; }
pay() { this.state.pay(this); }
ship() { this.state.ship(this); }
}
const order = new Order();
order.pay();
order.ship();
Python
class Pending:
def pay(self, order): order.state = Paid()
def ship(self, order): raise ValueError("Pay before shipping")
class Paid:
def pay(self, order): raise ValueError("Already paid")
def ship(self, order): order.state = Shipped()
class Shipped:
def pay(self, order): raise ValueError("Already shipped")
def ship(self, order): raise ValueError("Already shipped")
class Order:
def __init__(self): self.state = Pending()
def pay(self): self.state.pay(self)
def ship(self): self.state.ship(self)
order = Order()
order.pay()
order.ship()
State vs Strategy: Both delegate behavior. Strategy selects an
algorithm, usually supplied from outside. State represents an object's
lifecycle and commonly changes through transitions triggered by the
object.
21. Strategy
Intent: Define a family of algorithms, encapsulate each one, and
make them interchangeable.
Use when: Payment methods, pricing rules, sorting, authentication
mechanisms, or file export formats.
TypeScript
interface PaymentStrategy {
pay(amount: number): void;
}
class CardPayment implements PaymentStrategy {
pay(amount: number) { console.log("Card payment:", amount); }
}
class UpiPayment implements PaymentStrategy {
pay(amount: number) { console.log("UPI payment:", amount); }
}
class Checkout {
constructor(private strategy: PaymentStrategy) {}
setStrategy(strategy: PaymentStrategy) { this.strategy = strategy; }
pay(amount: number) { this.strategy.pay(amount); }
}
const checkout = new Checkout(new UpiPayment());
checkout.pay(500);
checkout.setStrategy(new CardPayment());
checkout.pay(700);
Python
class CardPayment:
def pay(self, amount): print("Card payment:", amount)
class UpiPayment:
def pay(self, amount): print("UPI payment:", amount)
class Checkout:
def __init__(self, strategy): self.strategy = strategy
def set_strategy(self, strategy): self.strategy = strategy
def pay(self, amount): self.strategy.pay(amount)
checkout = Checkout(UpiPayment())
checkout.pay(500)
checkout.set_strategy(CardPayment())
checkout.pay(700)
Why it helps: Instead of a growing if/elif block, the context
delegates to an implementation with a common contract. In Python, a
function or callable can also be a strategy.
22. Template Method
Intent: Define the skeleton of an algorithm in a base class while
allowing subclasses to override selected steps.
Use when: Several workflows share the same overall sequence but
differ in individual steps.
TypeScript
abstract class DataImporter {
importData() {
const raw = this.read();
const parsed = this.parse(raw);
this.save(parsed);
}
protected abstract read(): string;
protected abstract parse(raw: string): unknown;
protected save(data: unknown) { console.log("Saved:", data); }
}
class CsvImporter extends DataImporter {
protected read() { return "a,b,c"; }
protected parse(raw: string) { return raw.split(","); }
}
new CsvImporter().importData();
Python
from abc import ABC, abstractmethod
class DataImporter(ABC):
def import_data(self):
raw = self.read()
parsed = self.parse(raw)
self.save(parsed)
@abstractmethod
def read(self): ...
@abstractmethod
def parse(self, raw): ...
def save(self, data): print("Saved:", data)
class CsvImporter(DataImporter):
def read(self): return "a,b,c"
def parse(self, raw): return raw.split(",")
CsvImporter().import_data()
Strategy vs Template Method: Strategy composes a context with a
replaceable algorithm object. Template Method uses inheritance and
overrides selected steps of a fixed algorithm.
23. Visitor
Intent: Define a new operation over a set of object types without
placing that operation in each element class.
Use when: The object structure is relatively stable but new
operations (reports, exports, analysis) are added often.
TypeScript
interface Visitor {
visitCircle(circle: Circle): string;
visitRectangle(rectangle: Rectangle): string;
}
interface Shape {
accept(visitor: Visitor): string;
}
class Circle implements Shape {
constructor(public radius: number) {}
accept(visitor: Visitor) { return visitor.visitCircle(this); }
}
class Rectangle implements Shape {
constructor(public width: number, public height: number) {}
accept(visitor: Visitor) { return visitor.visitRectangle(this); }
}
class AreaVisitor implements Visitor {
visitCircle(c: Circle) { return String(Math.PI * c.radius ** 2); }
visitRectangle(r: Rectangle) { return String(r.width * r.height); }
}
const visitor = new AreaVisitor();
console.log(new Circle(2).accept(visitor));
console.log(new Rectangle(3, 4).accept(visitor));
Python
import math
class Circle:
def __init__(self, radius): self.radius = radius
def accept(self, visitor): return visitor.visit_circle(self)
class Rectangle:
def __init__(self, width, height):
self.width, self.height = width, height
def accept(self, visitor): return visitor.visit_rectangle(self)
class AreaVisitor:
def visit_circle(self, circle): return math.pi * circle.radius ** 2
def visit_rectangle(self, rectangle): return rectangle.width * rectangle.height
visitor = AreaVisitor()
print(Circle(2).accept(visitor))
print(Rectangle(3, 4).accept(visitor))
Trade-off: Visitor makes adding operations easy, but adding a new
element type requires updating visitors. It can also be awkward in
languages with limited support for double dispatch.
6. Common application and architecture patterns
These are widely used patterns, but they are not part of the original
23 GoF patterns.
Repository Pattern
Purpose: Encapsulate data-access logic behind a domain-oriented
interface so business logic does not depend directly on an ORM or
database API.
interface User { id: string; name: string; }
interface UserRepository {
findById(id: string): Promise<User | null>;
save(user: User): Promise<void>;
}
class UserService {
constructor(private users: UserRepository) {}
async getUser(id: string) {
const user = await this.users.findById(id);
if (!user) throw new Error("User not found");
return user;
}
}
from typing import Protocol
class UserRepository(Protocol):
def find_by_id(self, user_id: str): ...
def save(self, user): ...
class UserService:
def __init__(self, users: UserRepository):
self.users = users
def get_user(self, user_id):
user = self.users.find_by_id(user_id)
if user is None:
raise LookupError("User not found")
return user
ORM change: Keep the service dependent on the repository interface.
Replace the concrete repository implementation and its ORM-specific
queries/mapping. The schema, migrations, entity/model mapping, and
repository implementation may need changes depending on the ORM; the
service should ideally remain unchanged.
Service Layer
Purpose: Put application use cases behind service methods. A
controller handles HTTP concerns; a service coordinates business rules
and repositories.
class UserController {
constructor(private service: UserService) {}
getUser(id: string) { return this.service.getUser(id); }
}
class UserController:
def __init__(self, service):
self.service = service
def get_user(self, user_id):
return self.service.get_user(user_id)
Dependency Injection (DI)
Purpose: Supply a class's dependencies from outside rather than
having it construct concrete dependencies internally. This improves
testability and reduces coupling.
class UserService {
constructor(private readonly users: UserRepository) {}
}
class UserService:
def __init__(self, users):
self.users = users
NestJS has a built-in dependency-injection container. In Python,
dependencies are often wired manually or with a DI library.
MVC (Model--View--Controller)
- Model: Data and domain behavior.
- View: Presentation.
- Controller: Handles input and coordinates the use case.
MVC is an architectural pattern, not a GoF object-creation pattern.
Layered Architecture
A common backend flow:
HTTP Request
|
Controller -- validates/parses transport input
|
Service -- executes application/business use case
|
Repository -- abstracts persistence
|
Database
Keep responsibilities clear. Do not put SQL/ORM details in controllers
or HTTP response formatting in repository classes.
Unit of Work
Purpose: Coordinate multiple data changes as one transaction,
committing them together or rolling them back.
Use the transaction mechanism provided by your ORM/database. A
repository may participate in a Unit of Work, but do not confuse the
two: a repository abstracts access to a collection/aggregate; a Unit of
Work tracks and commits a set of changes.
CQRS (Command Query Responsibility Segregation)
Purpose: Separate operations that change state (commands) from
operations that read data (queries). It can use different models for
reads and writes, but does not require separate databases.
Use it when read and write workloads or models genuinely have different
needs. It adds complexity and is not necessary for every CRUD
application.
Event-Driven Architecture
Purpose: Components communicate by publishing and reacting to events
rather than calling every downstream component directly.
Use durable message brokers and idempotent consumers when events cross
process boundaries. An in-memory Observer implementation is not a
substitute for reliable distributed messaging.
7. Patterns in a layered backend
A practical backend can combine patterns without forcing every pattern
into every feature.
Controller
|
v
Service / Use Case ---- Strategy (select business algorithm)
| ---- Facade (coordinate a complex workflow)
|
v
Repository Interface
|
v
ORM-specific Repository Implementation
|
v
Database
Other useful placements:
- Factory: Select a provider or construct a configured service.
- Adapter: Wrap an external payment, email, or storage SDK behind your own interface.
- Decorator: Add logging, caching, metrics, or authorization around a service.
- Proxy: Add lazy loading or access checks.
- Observer / events: Notify other components after a meaningful domain event.
- Command: Represent background jobs or queued actions.
- State: Model order/payment lifecycle transitions.
- Chain of Responsibility: Process HTTP middleware or validation steps.
Example: changing an ORM
Suppose UserService calls UserRepository, and
DrizzleUserRepository implements that interface.
To move to another ORM:
- Keep the service and repository interface stable where possible.
- Implement a new repository using the new ORM.
- Update ORM-specific schema/model definitions and migrations.
- Update mapping between ORM records and domain objects if required.
- Change dependency-injection wiring to use the new implementation.
- Run repository integration tests and service unit tests.
The exact files depend on the project's architecture. The goal is to
isolate ORM-specific code in the persistence layer.
8. Testing checklist
For each pattern implementation, test behavior rather than only checking
that classes exist.
- [ ] Singleton: Repeated access returns the same instance; tests do not leak shared state.
- [ ] Factory Method / Abstract Factory: Correct concrete product or compatible product family is created.
- [ ] Builder: Required fields are enforced; optional configuration is applied correctly.
- [ ] Prototype: Copy is independent where deep-copy behavior is required.
- [ ] Adapter: Input/output translation is correct, including units and error cases.
- [ ] Bridge: Each abstraction works with each supported implementation.
- [ ] Composite: Leaf and nested composite operations produce the expected result.
- [ ] Decorator: Original behavior remains and added behavior runs in the correct order.
- [ ] Facade: The subsystem calls occur in the expected order; failures are handled.
- [ ] Flyweight: Shared intrinsic state is reused and is not mutated accidentally.
- [ ] Proxy: Access rules, lazy initialization, and caching behave correctly.
- [ ] Chain of Responsibility: Matching handler handles the request; unhandled requests have a defined outcome.
- [ ] Command: The right action executes; undo/redo works if implemented.
- [ ] Interpreter: Expressions evaluate correctly for normal and boundary inputs.
- [ ] Iterator: Traversal order and completion behavior are correct.
- [ ] Mediator: Components communicate through the mediator, not hidden direct references.
- [ ] Memento: Restoring a snapshot restores the expected state.
- [ ] Observer: Subscribers receive notifications and can unsubscribe.
- [ ] State: Valid transitions work and invalid transitions are rejected.
- [ ] Strategy: Each algorithm can be substituted without changing the context.
- [ ] Template Method: The overall algorithm order is stable and extension steps work.
- [ ] Visitor: Each element dispatches to the correct visitor operation.
9. Quick revision table
Pattern Category Remember it as
Singleton Creational One shared instance
Factory Method Creational Subclass decides which
product to create
Abstract Factory Creational Create a family of
related products
Builder Creational Build a complex object
step by step
Prototype Creational Create by copying an
existing object
Adapter Structural Convert an incompatible
interface
Bridge Structural Separate abstraction
and implementation
Composite Structural Treat a tree and its
leaves uniformly
Decorator Structural Wrap an object to add
behavior
Facade Structural One simple entry point
to a subsystem
Flyweight Structural Share repeated
intrinsic state
Proxy Structural Control access to
another object
Chain of Responsibility Behavioral Pass request through
handlers
Command Behavioral Turn a request into an
object
Interpreter Behavioral Evaluate a small
language/grammar
Iterator Behavioral Traverse without
exposing internals
Mediator Behavioral Centralize object
communication
Memento Behavioral Save and restore state
Observer Behavioral Notify subscribers of
changes
State Behavioral Behavior depends on
current state
Strategy Behavioral Swap algorithms
Template Method Behavioral Fixed algorithm
skeleton with
overridable steps
Visitor Behavioral Add operations over
object structures
Final advice
- Learn the problem first, then the pattern name.
- Implement a small example in TypeScript and Python.
- Identify the interface/abstraction, concrete implementations, and who owns object creation.
- Write tests for normal behavior and edge cases.
- Refactor only when the pattern makes the code easier to change or understand.
The best design is not the one containing the most patterns. It is the
simplest design that keeps responsibilities clear and makes likely
changes safe.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.