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("maya@example.com") .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("maya@example.com").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)...
