Fundamentals 14 min read

A Complete Guide to 23 Classic Design Patterns

This article systematically explains 23 fundamental design patterns—creational, structural, and behavioral—detailing their intent, typical use cases, and concrete examples such as Singleton for configuration managers, Factory Method for transport logistics, Builder for house construction, and many more, helping readers master pattern selection and application.

Subtle Storm
Subtle Storm
Subtle Storm
A Complete Guide to 23 Classic Design Patterns

Introduction

Design patterns are timeless concepts that frequently appear in software design exams, often phrased in English. This guide summarizes 23 classic patterns, grouped into three categories, with concise explanations and real‑world analogies drawn from textbooks and the web.

Creational Patterns (5)

1. Singleton

Ensures a class has only one instance in the entire system. Typical uses include configuration managers, loggers, and database connection pools where a single global instance prevents conflicts.

2. Factory Method

Defines an interface for creating objects while letting subclasses decide which concrete class to instantiate. Example: a logistics company initially ships by truck; when it adds sea transport, the createTransport() method in a subclass returns a Ship instead of a Truck, isolating the change.

3. Abstract Factory

Creates families of related products. Example: a UI component library that supports both Windows and Mac styles. The abstract factory defines createButton() and createTextBox(); concrete factories produce matching Windows or Mac components, allowing a style switch by swapping a single factory.

4. Builder

Separates a complex object’s construction from its representation. Building a house illustrates the process: lay foundation → erect walls → install doors/windows → roof. A Director orchestrates steps, while a Builder implements each step, finally delivering the Product.

5. Prototype

Clones existing objects via a clone() method when creation is costly (e.g., database queries or heavy calculations). Java’s String pool and Integer cache are practical examples of the prototype principle.

Structural Patterns (7)

6. Adapter

Converts one interface to another. Real‑world analogy: a power adapter changes 20 V laptop input to a 220 V socket. In code, an adapter wraps an incompatible legacy API, exposing a new interface.

7. Bridge

Separates two orthogonal dimensions (e.g., shape and color) to avoid class explosion. Shapes hold a reference to a color object, allowing independent extension of shapes or colors without combinatorial growth.

8. Composite

Treats individual objects and compositions uniformly. File systems exemplify this: both files and folders implement getName() and getSize(), and clients can operate on a tree without distinguishing leaf from composite.

9. Decorator

Adds responsibilities to objects dynamically. Java I/O streams demonstrate this: FileInputStreamBufferedInputStreamDataInputStream, each layer decorates the previous one, offering flexible runtime behavior.

10. Facade

Provides a simplified interface to a complex subsystem. In a restaurant, the waiter (facade) hides kitchen details; in micro‑services, an API Gateway acts as a facade, shielding clients from numerous backend services.

11. Flyweight

Shares intrinsic state to reduce memory usage when many similar objects exist. Character objects in a text editor share the same glyph data while external state (position, style) is supplied at use time.

12. Proxy

Supplies a surrogate that controls access to the real object. Types include remote proxy (hides network location via RPC), virtual proxy (lazy‑loads heavy resources like images), protection proxy (enforces access rights), and cache proxy (stores results to avoid recomputation). Spring AOP and JDK dynamic proxies are common implementations.

Behavioral Patterns (11)

13. Chain of Responsibility

Passes a request along a chain until an object handles it. Example: a company expense‑approval workflow where different amounts are approved by supervisors, managers, directors, or the CEO.

14. Command

Encapsulates a request as an object, enabling parameterization, queuing, logging, and undo. A remote‑control button maps to a LightOnCommand; pressing “undo” invokes the command’s undo() method.

15. Iterator

Provides sequential access to elements without exposing the underlying structure. Languages such as Java ( Iterator) and Python ( __iter__) implement this pattern, allowing different traversal strategies.

16. Mediator

Centralizes complex communication between many objects. A chat room mediates messages so participants only know the room, not each other. MVC controllers, message‑queue filters, and Spring Security filter chains are practical mediators.

17. Memento

Captures an object’s internal state without violating encapsulation, enabling later restoration. Game save files are classic examples: the Originator creates a memento of player stats, and the caretaker stores it.

18. Observer

Defines a one‑to‑many dependency; when the subject changes, all observers are notified. Used in event‑driven programming, stock price updates, UI button clicks, and publish‑subscribe systems.

19. State

Allows an object to alter its behavior when its internal state changes, appearing as if it changed class. Order processing (e.g., Pending → Paid → Shipped → Completed) benefits from state objects instead of tangled if‑else logic.

20. Strategy

Encapsulates interchangeable algorithms. E‑commerce promotion strategies (discount, full‑reduction, buy‑one‑get‑one) are implemented as separate strategy classes, injected where needed without modifying core flow.

21. Template Method

Defines the skeleton of an algorithm in a base class, delegating specific steps to subclasses. Brewing tea vs. coffee follows the same high‑level steps (boil water → add ingredient → pour), with subclasses providing the ingredient‑specific details. Frameworks like JUnit, Spring’s JdbcTemplate, and many libraries rely on this pattern.

22. Visitor

Adds new operations to existing object structures without changing them. In a company hierarchy, HR, finance, and other departments each need different calculations on the same employee tree; visitors encapsulate these operations.

23. Interpreter

Defines a grammar for a language and an interpreter to evaluate sentences. SQL parsers, regular‑expression engines, and scripting language interpreters use this pattern, constructing classes for each grammar rule and composing them to evaluate complex expressions.

Conclusion

If any pattern remains unclear, readers are encouraged to comment for deeper, scenario‑specific discussions.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

design patternsBehavioralCreationalStructuralSingletonObserverFactory MethodBuilder
Subtle Storm
Written by

Subtle Storm

The micro era's marvels are boundlessly subtle.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.