Design patterns every developer should know are not magic tricks. They are names for solutions that keep showing up in real code, and knowing the names lets you spot the solution faster and talk about it with your team in one word instead of a paragraph. This guide covers the patterns you will actually meet in day-to-day work, with short JavaScript examples for each one, so you can recognise them in the wild and use them when they fit.
Design patterns every developer should know: the short list
Patterns fall into three groups: creational patterns that control how objects are made, structural patterns that shape how objects are composed, and behavioural patterns that decide how objects talk to each other. You do not need to memorise all twenty-three patterns from the classic Gang of Four book. A handful covers most of the situations you will meet, and the rest you can look up when you need them. If you are new to functions that return functions, our guide to JavaScript closures with real code examples will make several of the examples below easier to follow.
Singleton: one shared instance
A singleton makes sure a class has only one instance and gives everyone a single way to reach it. Configuration objects and database connections are the usual cases, since two different configs in one app cause strange bugs. Here is a simple version:
class Config {
constructor() {
if (Config.instance) return Config.instance;
this.settings = {};
Config.instance = this;
}
static getInstance() {
if (!Config.instance) Config.instance = new Config();
return Config.instance;
}
}
const a = Config.getInstance();
const b = Config.getInstance();
console.log(a === b); // true
Use it sparingly. A singleton is shared global state with a nicer name, and tests can suffer when one test changes the shared instance and the next test inherits the mess. Reach for it when exactly one instance is a real requirement, not just a convenience.
Factory Method: let a function build the object
A factory hides the details of creating an object behind a function. The caller asks for a thing by name and gets the right object back, without knowing the class that built it:
function createNotifier(channel) {
if (channel === "email") return new EmailNotifier();
if (channel === "sms") return new SmsNotifier();
return new PushNotifier();
}
const notifier = createNotifier("sms");
notifier.send("Your order shipped");
This keeps creation logic in one place. When you add a new channel, you edit the factory, not every file that creates a notifier. It pairs well with the strategy pattern below, since a factory can hand out different strategies behind the same interface.
Observer: notify everyone who cares
The observer pattern lets an object broadcast an event to a list of subscribers, without knowing who they are. Event emitters, state stores, and notification systems all use it. Here is a tiny version:
class EventBus {
constructor() { this.listeners = {}; }
on(event, fn) {
this.listeners[event] = this.listeners[event] || [];
this.listeners[event].push(fn);
}
emit(event, data) {
(this.listeners[event] || []).forEach((fn) => fn(data));
}
}
const bus = new EventBus();
bus.on("order-paid", (order) => console.log("Paid:", order.id));
bus.emit("order-paid", { id: 42 });
The sender and the receivers stay separate, so you can add a new listener without touching the code that emits the event. The risk is a tangle of hidden connections: when ten listeners react to one event, tracing a bug means tracing all ten. Keep the event names clear and the listeners short. The same idea shows up in larger systems too, including AI agents with memory patterns, where agents react to events in a shared loop.
Strategy: swap the algorithm
The strategy pattern stores different ways of doing the same job and lets the caller pick one at runtime. Shipping costs are a clean example:
const shipping = {
standard: (weight) => weight * 2,
express: (weight) => weight * 5,
overnight: (weight) => weight * 9,
};
function shippingCost(method, weight) {
return shipping[method](weight);
}
console.log(shippingCost("express", 3)); // 15
Adding a new method means adding one entry. The calling code never changes, and each strategy can be tested on its own. If you are building an API that exposes different behaviours per client, our guide on REST vs GraphQL covers how the same choice looks at the API level.
Decorator: add behaviour without changing the object
A decorator wraps an object and adds behaviour around it, leaving the original untouched. Logging, caching, and validation are the usual cases:
function withLogging(fn, name) {
return (...args) => {
console.log("Calling", name);
const result = fn(...args);
console.log("Done", name);
return result;
};
}
const saveUser = withLogging((user) => {
/* write to database */
}, "saveUser");
Decorators stack: you can wrap a function in logging, then in timing, then in retry logic, and each wrapper stays small and testable. Python decorators use the same idea with nicer syntax, and the concept transfers directly between languages.
Adapter: make two incompatible things work together
An adapter translates one interface into another so existing code can use a new library without a rewrite. Say a payment library expects a different shape than your code produces:
class PaymentAdapter {
constructor(gateway) { this.gateway = gateway; }
charge(amount) {
return this.gateway.processPayment({
total: amount,
currency: "USD",
});
}
}
const payment = new PaymentAdapter(new StripeGateway());
payment.charge(49);
Your code calls charge, the adapter translates, and the gateway never knows the difference. When you swap gateways later, you write a new adapter and the rest of the app stays the same. Adapters also help when you integrate a third-party API whose naming does not match your codebase, which is a common reason to document your APIs well so the next person understands the translation.
Repository: one place for data access
The repository pattern puts all data access behind one interface, so the rest of the app never talks to the database directly:
class UserRepository {
async findById(id) { /* query database */ }
async findByEmail(email) { /* query database */ }
async save(user) { /* insert or update */ }
}
const users = new UserRepository();
const user = await users.findById(7);
Because the service layer only knows the repository, you can swap the database, add caching, or mock the repository in tests without touching business logic. It is one of the most useful patterns in real projects, and it quietly enforces the single-responsibility idea as well.
How to pick the right pattern
Start from the problem, not the pattern. If object creation is messy, look at factories. If behaviour changes at runtime, look at strategy. If many parts need to react to one event, look at observer. If you find yourself naming a pattern before you have named the problem, stop: that is how simple code turns into a pattern showcase nobody wants to maintain. A pattern earns its place when it removes duplication or makes a future change cheaper, and the best sign you chose well is that the next change takes less time than the last one. Learn these seven first, use them where they fit, and look the others up when a problem smells like one you have seen before.