Design Patterns for Beginners: The Ones You Actually Use
Design patterns are named solutions to recurring problems. Learn the handful that appear constantly in real code, with examples and when to skip them.
By Velloreth
What a design pattern is
A design pattern is a named solution to a recurring design problem. It is not a library, not a snippet, and not a rule. It is a description of how to structure code to solve a problem that keeps appearing.
The value is threefold:
- A shared vocabulary. Saying “use a strategy here” communicates a design in three words.
- Proven solutions. The pattern has been used and refined by many people.
- A starting point. You do not have to invent a structure from scratch.
The classic catalogue is Design Patterns by Gamma, Helm, Johnson, and Vlissides — the “Gang of Four” — which describes 23 patterns. Most application developers use six or seven of them regularly.
Strategy
Problem: you have several interchangeable algorithms and want to choose at runtime.
interface ShippingStrategy {
cost(weight: number): number;
}
class StandardShipping implements ShippingStrategy {
cost(weight: number) { return weight * 0.5; }
}
class ExpressShipping implements ShippingStrategy {
cost(weight: number) { return weight * 2 + 10; }
}
class Order {
constructor(private shipping: ShippingStrategy) {}
totalShipping(weight: number) {
return this.shipping.cost(weight);
}
}
The order does not know which shipping method it uses. The strategy is injected, so it can be swapped, tested, and extended without touching Order.
Where you see it: payment methods, pricing rules, sorting comparators, compression algorithms, authentication providers.
The modern form: in languages with first-class functions, a strategy is often just a function. You do not need a class hierarchy for a single method.
Factory
Problem: you need to create objects without the caller knowing which concrete class to instantiate.
interface Notification {
send(message: string): void;
}
class EmailNotification implements Notification {
send(message: string) { /* ... */ }
}
class SMSNotification implements Notification {
send(message: string) { /* ... */ }
}
function createNotification(channel: string): Notification {
switch (channel) {
case 'email': return new EmailNotification();
case 'sms': return new SMSNotification();
default: throw new Error(`Unknown channel: ${channel}`);
}
}
The caller asks for a notification by name and gets one. Adding a channel means editing the factory, not every call site.
Where you see it: database connection creation, parser selection, UI component construction, dependency injection containers.
The caution: a factory with one product and no variation is just a function call with extra steps.
Observer
Problem: one object changes and several others need to know.
type Listener<T> = (event: T) => void;
class EventEmitter<T> {
private listeners: Listener<T>[] = [];
on(listener: Listener<T>): () => void {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter((l) => l !== listener);
};
}
emit(event: T): void {
for (const listener of this.listeners) listener(event);
}
}
The emitter does not know who is listening. Subscribers register and are notified. The returned unsubscribe function is important — without it, listeners accumulate and leak.
Where you see it: DOM event listeners, React state subscriptions, message buses, reactive frameworks, WebSocket handlers.
The caution: observers make control flow hard to follow, because the connection between emitter and listener is not visible at the call site. Use them where decoupling is genuinely needed.
Adapter
Problem: you need to use a class whose interface does not match what your code expects.
interface PaymentGateway {
charge(amount: number, token: string): Promise<Receipt>;
}
class StripeAdapter implements PaymentGateway {
constructor(private stripe: StripeClient) {}
async charge(amount: number, token: string): Promise<Receipt> {
const result = await this.stripe.charges.create({
amount: amount * 100, // Stripe uses cents
source: token,
});
return { id: result.id, status: result.status };
}
}
The adapter translates between your interface and the third party’s. Your code depends on PaymentGateway, so swapping providers means writing a new adapter, not changing business logic.
Where you see it: third-party API integration, legacy system integration, database drivers, logging libraries.
Decorator
Problem: you want to add behaviour to an object without modifying its class or subclassing.
interface DataSource {
read(): string;
}
class FileDataSource implements DataSource {
constructor(private path: string) {}
read() { return readFileSync(this.path, 'utf8'); }
}
class EncryptedDataSource implements DataSource {
constructor(private wrapped: DataSource) {}
read() { return decrypt(this.wrapped.read()); }
}
class CompressedDataSource implements DataSource {
constructor(private wrapped: DataSource) {}
read() { return decompress(this.wrapped.read()); }
}
const source = new CompressedDataSource(
new EncryptedDataSource(new FileDataSource('data.txt')),
);
Each decorator wraps another and adds behaviour. They compose in any order and any combination, which subclassing cannot do without a class per combination.
Where you see it: middleware, HTTP client interceptors, stream transformations, Python decorators, React higher-order components.
Repository
Problem: you want to separate domain logic from data access.
interface UserRepository {
findById(id: string): Promise<User | null>;
findByEmail(email: string): Promise<User | null>;
save(user: User): Promise<void>;
delete(id: string): Promise<void>;
}
class PostgresUserRepository implements UserRepository {
async findById(id: string) {
const row = await db.query('SELECT * FROM users WHERE id = $1', [id]);
return row ? toUser(row) : null;
}
// ...
}
The domain code works with User objects and never sees SQL. Tests use an in-memory implementation. Swapping databases means writing a new repository.
Where you see it: almost every layered application, especially with domain-driven design.
The caution: a repository that just forwards every ORM method adds a layer without abstraction. It earns its keep when it hides real complexity or enables testing.
Patterns you can skip
Several classic patterns exist to work around limitations that modern languages have removed.
| Pattern | Why it is less needed now |
|---|---|
| Singleton | Modules and dependency injection provide single instances |
| Iterator | Built into most languages as for-of, generators |
| Command | Closures and first-class functions cover most cases |
| Abstract factory | Often replaced by dependency injection |
| Builder | Named arguments and object literals cover simple cases |
| Prototype | Object spread and structured clone |
This is not to say they are useless. They appear in frameworks and in languages without these features. But reaching for them in modern application code is usually unnecessary.
The misuse: over-patterning
The most common mistake is applying patterns where the problem does not exist.
// Over-engineered: a factory for one implementation
interface UserServiceFactory {
create(): UserService;
}
class UserServiceFactoryImpl implements UserServiceFactory {
create(): UserService { return new UserService(); }
}
This adds two types and a layer of indirection to do what new UserService() does. The pattern is present; the problem it solves is not.
The symptoms of over-patterning:
- Interfaces with exactly one implementation and no test double.
- Factories that construct one type.
- Abstract classes with one subclass.
- Layers that only forward calls.
- Names that describe the pattern rather than the domain.
The rule is: introduce a pattern when the problem is real and recurring, not in anticipation of a problem that might appear.
Practical guidance
- Learn strategy, factory, observer, adapter, decorator, and repository — they cover most real needs.
- Name the problem first, then reach for the pattern that solves it.
- Prefer the simplest structure that solves the problem.
- Use patterns as vocabulary in design discussions.
- Do not abstract for a single case — wait for the second or third.
- Recognise anti-patterns — god objects, copy-paste, shotgun surgery.
- Remember that patterns are descriptive, not prescriptive. If your code solves the problem well without a named pattern, that is fine.
For the related principles, see SOLID principles explained and composition vs inheritance. For the practical application, dependency injection without a framework and interfaces vs abstract classes.
Quotable summary
A design pattern is a named, reusable solution to a recurring design problem, not code you copy. The patterns that appear most in application code are strategy for interchangeable algorithms, factory for decoupled creation, observer for one-to-many notification, adapter for interface translation, decorator for composable behaviour, and repository for separating domain logic from data access. Patterns provide a shared vocabulary and proven structures, but applying them where the problem does not exist adds indirection and makes code harder to follow, which is the most common misuse. Many classic patterns existed to work around language limitations, so in modern languages some are built in or unnecessary.