Design Patterns Every Developer Should Know
November 28, 2026 · 12 min read

Every developer eventually meets the same problems: choosing between several ways of doing something at runtime, notifying other parts of an app when something happens, wrapping a third-party library that does not fit your code, or adding caching without rewriting a class. Design patterns are proven, named solutions to these recurring problems. Knowing them helps you write cleaner code, read other people's code faster and discuss designs precisely: "use a strategy here" says in three words what would otherwise take a paragraph.
The idea was popularised in 1994 by the book Design Patterns: Elements of Reusable Object-Oriented Software, written by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, the "Gang of Four", which catalogued 23 patterns. Three decades later, the vocabulary is everywhere, from React hooks and Express middleware to cloud architectures. This guide explains the design patterns every developer should know, with one runnable TypeScript example that uses six of them together, plus advice on when patterns help and when they become over-engineering.
What Are Design Patterns?
A design pattern is a reusable description of how to solve a common design problem, including the forces involved and the trade-offs. It is not a library or a snippet to paste; it is a shape that you adapt to your language and situation. The classic patterns fall into three families:
| Family | What it deals with | Examples |
|---|---|---|
| Creational | How objects are created | Factory Method, Abstract Factory, Builder, Prototype, Singleton |
| Structural | How objects are composed into larger structures | Adapter, Decorator, Facade, Proxy, Composite, Bridge |
| Behavioural | How objects communicate and share responsibility | Strategy, Observer, Command, State, Iterator, Chain of Responsibility |
Patterns and the SOLID principles work hand in hand. The principles describe the qualities good designs share, such as being open for extension and depending on abstractions; patterns are concrete ways to achieve them.
Six Patterns in One Checkout
The example below is a small online shop checkout that uses six of the most common patterns. Each section is labelled, and the explanations that follow refer back to it. It runs directly with Node.js 22.18 or later, which strips TypeScript types natively, and passes a strict type check:
// patterns.ts: six design patterns you will meet in almost every codebase, in one runnable file
// 1. Strategy: swap an algorithm at runtime behind one interface
interface ShippingStrategy {
cost(weightKg: number): number;
}
const standard: ShippingStrategy = { cost: (kg) => 3 + kg * 0.5 };
const express: ShippingStrategy = { cost: (kg) => 8 + kg * 1.2 };
const shippingFor = (choice: "standard" | "express"): ShippingStrategy =>
choice === "express" ? express : standard;
// 2. Observer: let other parts of the app react to an event without the sender knowing them
type Listener<T> = (event: T) => void;
class EventBus<T> {
private listeners: Listener<T>[] = [];
subscribe(listener: Listener<T>): () => void {
this.listeners.push(listener);
return () => { this.listeners = this.listeners.filter((l) => l !== listener); };
}
publish(event: T) { for (const l of this.listeners) l(event); }
}
// 3. Factory: one place decides which concrete class to create
interface PaymentProvider {
pay(amount: number): string;
}
class CardProvider implements PaymentProvider {
pay(amount: number) { return `card charged ${amount.toFixed(2)}`; }
}
class WalletProvider implements PaymentProvider {
pay(amount: number) { return `wallet debited ${amount.toFixed(2)}`; }
}
function createPaymentProvider(kind: string): PaymentProvider {
if (kind === "card") return new CardProvider();
if (kind === "wallet") return new WalletProvider();
throw new Error(`Unknown payment provider: ${kind}`);
}
// 4. Adapter: make an old or third-party API fit the interface your code expects
interface Notifier {
notify(to: string, text: string): string;
}
const legacySmsGateway = { // imagine a vendor SDK with a different shape
sendSMS: (payload: { msisdn: string; body: string }) => `SMS to ${payload.msisdn}: ${payload.body}`,
};
class SmsAdapter implements Notifier {
notify(to: string, text: string) { return legacySmsGateway.sendSMS({ msisdn: to, body: text }); }
}
// 5. Decorator: add behaviour (here caching) without changing the original class
interface PriceSource {
priceOf(sku: string): number;
}
class SlowPriceService implements PriceSource {
calls = 0;
priceOf(sku: string) { this.calls++; return sku === "MOUSE" ? 25 : 10; }
}
class CachedPrices implements PriceSource {
private cache = new Map<string, number>();
private inner: PriceSource;
constructor(inner: PriceSource) { this.inner = inner; }
priceOf(sku: string) {
if (!this.cache.has(sku)) this.cache.set(sku, this.inner.priceOf(sku));
return this.cache.get(sku)!;
}
}
// 6. Builder: assemble a complex object step by step with readable code
class OrderBuilder {
private items: { sku: string; qty: number }[] = [];
private shipping: ShippingStrategy = standard;
private note = "";
add(sku: string, qty = 1) { this.items.push({ sku, qty }); return this; }
ship(strategy: ShippingStrategy) { this.shipping = strategy; return this; }
withNote(note: string) { this.note = note; return this; }
build(prices: PriceSource) {
const goods = this.items.reduce((sum, i) => sum + prices.priceOf(i.sku) * i.qty, 0);
const weight = this.items.reduce((sum, i) => sum + i.qty * 0.4, 0);
return { items: this.items, total: goods + this.shipping.cost(weight), note: this.note };
}
}
// Putting them together
const slow = new SlowPriceService();
const prices = new CachedPrices(slow);
const order = new OrderBuilder().add("MOUSE", 2).add("CABLE").ship(shippingFor("express")).withNote("Leave at reception").build(prices);
prices.priceOf("MOUSE");
const bus = new EventBus<{ total: number }>();
const sms = new SmsAdapter();
bus.subscribe((e) => console.log(sms.notify("+920000000000", `Order confirmed: ${e.total.toFixed(2)}`)));
bus.subscribe((e) => console.log(createPaymentProvider("card").pay(e.total)));
bus.publish({ total: order.total });
console.log(`price lookups hitting the slow service: ${slow.calls} (one per product; repeats come from the cache)`);
Output:
SMS to +920000000000: Order confirmed: 69.44
card charged 69.44
price lookups hitting the slow service: 2 (one per product; repeats come from the cache)
The order total is 60 for the goods plus 9.44 for express shipping on 1.2 kg. Two subscribers react to the same "order placed" event, and the slow price service is called only twice even though prices were looked up three times. Now let's look at each pattern.
1. Strategy Pattern
Problem: you have several interchangeable ways of doing one thing, such as shipping rates, tax rules, sorting algorithms or pricing plans, and you need to choose between them at runtime. Solution: put each algorithm behind the same interface and pass the one you need. In the example, standard and express both implement ShippingStrategy, and the order does not care which it receives.
Strategy is the usual cure for long if/else chains, and it is how you follow the open/closed principle in practice: a new shipping option is a new object, not an edit to existing code. In JavaScript, a strategy is often just a function.
2. Observer Pattern
Problem: when something happens, several other parts of the system need to react, and the code that triggers the event should not need to know about all of them. Solution: let listeners subscribe to a subject and notify them when the event occurs. The EventBus in the example publishes an "order placed" event, and the SMS notification and the payment step subscribe independently.
Observer is everywhere: DOM events, Node.js's EventEmitter, state management libraries, webhooks and message queues. Its main pitfall is forgetting to unsubscribe, which causes memory leaks and duplicate handling; that is why subscribe in the example returns an unsubscribe function, the same convention React's effect clean-ups use.
3. Factory Pattern
Problem: code needs to create objects, but which concrete class to create depends on configuration, user choice or environment. Solution: put the creation logic in one place. createPaymentProvider decides whether to build a card or wallet provider, and the rest of the code only sees the PaymentProvider interface. Adding a new provider changes the factory, not every place that takes payments.
Factories are also how frameworks create database drivers, loggers and storage clients from configuration. Keep them simple; a factory that needs its own factory is usually a sign of over-engineering.
4. Adapter Pattern
Problem: a third-party library, legacy system or vendor API has an interface that does not match what your code expects. Solution: write a small class that translates between them. SmsAdapter makes a vendor SDK with a sendSMS method and a msisdn field look like your app's simple Notifier interface.
Adapters protect your codebase from vendors. If you switch SMS or payment providers, only the adapter changes. They are also the standard way to bring legacy systems into new architectures without spreading their quirks everywhere.
5. Decorator Pattern
Problem: you want to add behaviour, such as caching, logging, retries or access checks, to an object without changing its class. Solution: wrap it in another object with the same interface that adds the behaviour and delegates the rest. CachedPrices wraps the slow price service, and callers cannot tell the difference except that it is faster.
Because decorators share an interface, they stack: a logged, retried, cached client is three thin wrappers. Our Redis caching guide shows the same idea at infrastructure level. Note that TypeScript's @decorator syntax is a related language feature, not the same thing as this pattern.
6. Builder Pattern
Problem: constructing an object needs many optional parts, and a constructor with eight parameters is unreadable and error-prone. Solution: build it step by step with clearly named methods. OrderBuilder lets you write add, ship and withNote calls that read like a sentence. Query builders, HTTP request builders and test-data builders all use this pattern.
Other Patterns Worth Knowing
- Singleton: one shared instance, such as a configuration object or connection pool. Use sparingly, because hidden global state makes testing harder; in JavaScript, a module that exports one instance usually does the job.
- Facade: a simple interface in front of a complicated subsystem, like a
sendInvoicefunction hiding PDF generation, storage and email. - Proxy: an object that controls access to another, for lazy loading, permission checks or remote calls.
- Command: wraps an action as an object, enabling undo and redo, queues and audit logs.
- Chain of Responsibility: passes a request along a chain of handlers, exactly how Express and other web framework middleware work.
- Repository: hides data access behind a collection-like interface, so business logic does not depend on SQL details. The same thinking applies when routing data across servers, as in our guide to database sharding, where the routing logic belongs behind one interface.
Beyond these code-level patterns sit architectural patterns such as MVC, event-driven architecture, CQRS and the circuit breaker, which our comparison of microservices vs monoliths touches on.
Design Patterns in Modern JavaScript and React
Patterns look different in modern JavaScript, because functions are first-class values and modules provide encapsulation. A strategy is often a function passed as an argument. React's context acts as lightweight dependency injection, custom hooks package reusable behaviour, and higher-order components are decorators. Express middleware is a chain of responsibility, and state libraries implement observer. If you work with the MERN stack, you already use several of these patterns daily, even if nobody named them.
Anti-Patterns and Overuse
Patterns are tools, not goals. Common mistakes include:
- Pattern-first design: adding factories, strategies and observers before there is a second variant or a second listener.
- The golden hammer: applying a favourite pattern everywhere, whether or not the problem fits.
- The god object: the opposite failure, where one class does everything and no pattern has been applied at all.
- Indirection soup: so many layers that following a single request means opening ten files.
A good rule: introduce a pattern when a real change becomes painful, and name it in the code or comments so the next developer recognises it.
Design Patterns and AI Coding Assistants
Pattern names are excellent prompts. "Wrap the SMS provider's SDK in an adapter that implements our Notifier interface" is far more precise than "add SMS support", and AI coding assistants know these patterns well. Put the patterns your team prefers into your project's specs and agent instructions, as described in our guide to spec-driven development, and use them as a checklist when reviewing generated code. Without that guidance, AI tools often produce the tangled, god-object code that makes vibe coding hard to maintain.
How to Learn Design Patterns
- Start with the six patterns above; they cover most day-to-day situations.
- Read clear explanations with diagrams, such as the free catalogue at Refactoring.Guru, then the Gang of Four book for depth.
- Look for patterns in libraries you already use, such as Express, React and your ORM.
- Practise by refactoring: take a long function with type-based
ifchains and apply Strategy or Factory. - Discuss designs using pattern names in code reviews, so the vocabulary becomes shared.
Frequently Asked Questions
What are design patterns?
Design patterns are reusable, named solutions to common software design problems, such as choosing an algorithm at runtime, reacting to events or adapting an incompatible interface. They describe a structure to adapt, not code to copy.
What are the three types of design patterns?
The classic categories are creational patterns, which handle object creation; structural patterns, which handle how objects are composed; and behavioural patterns, which handle how objects communicate and share responsibilities.
Which design patterns should I learn first?
Strategy, Observer, Factory, Adapter, Decorator and Builder are the most useful starting set, followed by Facade, Command, Repository and Singleton, including Singleton's drawbacks.
Are design patterns still relevant in 2027?
Yes. The implementation details change with languages and frameworks, but the problems they solve remain, and pattern names are a precise way to communicate designs to colleagues and to AI coding assistants.
Do design patterns apply to JavaScript and React?
Yes, often in lighter forms. Functions act as strategies, context provides dependency injection, hooks package behaviour, higher-order components act as decorators and Express middleware is a chain of responsibility.
What is the difference between design patterns and SOLID principles?
SOLID principles describe qualities of good design, such as single responsibility and depending on abstractions. Design patterns are concrete, reusable structures that help achieve those qualities in specific situations.
Build Software That Is Easy to Change
We design and build maintainable web and mobile applications, refactor tangled codebases with proven design patterns and set standards that keep AI-assisted code clean. Talk to our team about your next project or code review.
