Comprehensive Overview of 23 Design Patterns with Examples and Code
This article provides a systematic, example‑driven guide to all 23 classic design patterns—covering creational, structural, and behavioral types—explaining their intent, real‑world analogies, benefits, and offering clear diagrams and runnable code snippets to illustrate each pattern in practice.
This article systematically introduces 23 classic design patterns, providing easy-to-understand examples, structure diagrams, and code implementations. It serves as a learning guide for understanding the purpose, benefits, and real‑world analogies of each pattern.
What Is a Design Pattern?
The concept of design patterns was popularized by the book "Design Patterns: Elements of Reusable Object‑Oriented Software" (1994). The book presents 23 patterns that solve common software design problems. Patterns are not algorithms or concrete implementations; they are abstract ideas that help achieve high cohesion, low coupling, and better reusability.
Creational Patterns (5)
Creational patterns provide mechanisms for object creation, increasing flexibility and reusability of existing code.
Singleton : Guarantees a class has only one instance and provides a global access point.
Prototype : Creates new objects by copying an existing prototype.
Builder : Constructs complex objects step by step.
Factory Method : Defines an interface for creating an object, but lets subclasses decide which class to instantiate.
Abstract Factory : Produces families of related objects without specifying concrete classes.
Code example for Singleton (JavaScript/TypeScript):
class Singleton {
constructor() {
this.instance = null; // singleton flag
}
getInstance() {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
function clientCode() {
const s1 = Singleton.getInstance();
const s2 = Singleton.getInstance();
if (s1 === s2) {
console.log('Same instance');
} else {
console.log('Different instances');
}
}
clientCode(); // Same instanceCode example for Prototype:
class Prototype {
constructor(name) {
this.name = name;
}
setName(name) {
this.name = name;
}
clone() {
return new Prototype(this.name);
}
}
function clientCode() {
const p1 = new Prototype('Prototype');
const p2 = p1.clone();
if (p1.name === p2.name) {
console.log('Property copied');
}
p2.setName('Cloned Prototype');
if (p2.name === 'Cloned Prototype') {
console.log('Method copied without class dependency');
}
}
clientCode();Structural Patterns (7)
Structural patterns explain how to compose objects and classes into larger structures while keeping the structures flexible and efficient.
Bridge : Decouples an abstraction from its implementation so both can vary independently.
Facade : Provides a simplified interface to a complex subsystem.
Composite : Treats individual objects and compositions uniformly.
Decorator : Dynamically adds responsibilities to objects.
Adapter : Allows incompatible interfaces to work together.
Proxy : Provides a placeholder or access control to another object.
Flyweight : Shares common state among many objects to reduce memory usage.
Code example for Adapter:
class Target {
request() {
return "Target: default behavior.";
}
}
class Adaptee {
specificRequest() {
return ".eetpadA eht fo roivaheb laicepS"; // reversed string
}
}
class Adapter extends Target {
constructor(adaptee) {
super();
this.adaptee = adaptee;
}
request() {
const result = this.adaptee.specificRequest().split('').reverse().join('');
return `Adapter: (TRANSLATED) ${result}`;
}
}
function clientCode(target) {
console.log(target.request());
}
clientCode(new Target()); // Target: default behavior.
const adapter = new Adapter(new Adaptee());
clientCode(adapter); // Adapter: (TRANSLATED) Special behavior of the Adaptee.Behavioral Patterns (11)
Behavioral patterns focus on efficient communication and responsibility delegation among objects.
Iterator : Provides a way to access elements of a collection sequentially without exposing its underlying representation.
Interpreter : Defines a language grammar and an interpreter to evaluate sentences.
Observer : Implements a publish‑subscribe mechanism.
Mediator : Centralizes complex communications and control between related objects.
Visitor : Separates algorithms from the objects on which they operate.
State : Allows an object to alter its behavior when its internal state changes.
Memento : Captures and restores an object's internal state without violating encapsulation.
Strategy : Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
Template Method : Defines the skeleton of an algorithm in a base class, letting subclasses override specific steps.
Chain of Responsibility : Passes a request along a chain of handlers until one handles it.
Command : Encapsulates a request as an object, allowing parameterization, queuing, and undoable operations.
Code example for Command pattern:
interface Command { execute(): void; }
class SimpleCommand implements Command {
constructor(private payload: string) {}
execute() { console.log(`SimpleCommand: printing (${this.payload})`); }
}
class ComplexCommand implements Command {
constructor(private receiver: Receiver, private a: string, private b: string) {}
execute() {
console.log('ComplexCommand: delegating to receiver.');
this.receiver.doSomething(this.a);
this.receiver.doSomethingElse(this.b);
}
}
class Receiver {
doSomething(a: string) { console.log(`Receiver: working on (${a})`); }
doSomethingElse(b: string) { console.log(`Receiver: also working on (${b})`); }
}
class Invoker {
private onStart?: Command;
private onFinish?: Command;
setOnStart(cmd: Command) { this.onStart = cmd; }
setOnFinish(cmd: Command) { this.onFinish = cmd; }
doSomethingImportant() {
console.log('Invoker: pre‑action?');
this.onStart?.execute();
console.log('Invoker: ...doing important work...');
console.log('Invoker: post‑action?');
this.onFinish?.execute();
}
}
const invoker = new Invoker();
invoker.setOnStart(new SimpleCommand('Say Hi!'));
invoker.setOnFinish(new ComplexCommand(new Receiver(), 'Send email', 'Save report'));
invoker.doSomethingImportant();Reference: Alexander Shvets, Dive‑into Design Patterns , Finelybook, 2019.
DaTaobao Tech
Official account of DaTaobao Technology
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.