Key Takeaways
Treat patterns as adaptable blueprints, not snippets to paste into code
Patterns name recurring designs. A design pattern describes a reusable arrangement of objects for a recurring software problem. It is not a finished code sample: developers adapt its roles and relationships to their language and situation. An algorithm is more like a precise sequence of steps; a pattern leaves implementation details open, like a building plan that can be realized in different materials.
Names make designs discussable. The book covers 22 classic patterns, grouped by purpose: creating objects, arranging structures, and coordinating behavior. Their value is not only reuse. A team can use a shared name to discuss a design without rebuilding its explanation from scratch. Patterns were discovered by recognizing solutions that kept recurring, not invented as mandatory recipes.
The blueprint analogy is useful because it separates a design idea from its implementation. That distinction also sets a practical test: does the pattern clarify a real constraint, such as varying creation or coordinating events, or merely add classes? Shared vocabulary can speed collaboration, but a label is not an argument. Naming a design Factory Method does not explain why its extra indirection is worth maintaining. The useful discussion starts with the problem the name points to.
Put likely-to-change behavior behind stable interfaces
Model only what matters. Object-oriented programming bundles data and related behavior into objects, made from class blueprints. Abstraction selects the details relevant to a particular context: an airplane model for a booking app needs seats and availability, while a flight simulator needs flight behavior. Encapsulation protects internal state and exposes a controlled interface. Polymorphism lets code call the appropriate implementation through that shared interface, without knowing an object's concrete class.
Contain the blast radius. The book's e-commerce example separates tax calculation from order-total logic. When tax rules change, the calculation can change without disturbing the rest of the method. It also distinguishes relationships: a dependency means changes in one class may affect another; an association is a persistent link; aggregation and composition describe containment, with composition tying a component's life cycle to its container.
The important design move is not adding an interface everywhere. It is deciding which knowledge a component truly needs, then exposing only that contract. This resembles boundary design in other technical fields: a stable boundary lets the interior change without forcing every neighbor to change too. The tax example makes the payoff concrete because policy changes are expected while the order's broader responsibility remains steady. An abstraction with no meaningful variation, however, can become ceremony rather than protection.
Use composition to vary behavior without breeding subclasses
Prefer delegation for independent choices. Inheritance reuses behavior by extending a parent class, but subclasses inherit its interface and become sensitive to changes in its internals. When a car catalog varies by vehicle type, engine, and navigation, representing every combination as a subclass multiplies classes. Composition instead lets a car hold and delegate to separate engine and navigation objects, which can be combined or replaced independently.
Keep design principles practical. SOLID names five aims: give a class one coherent reason to change; allow extension without routinely editing stable code; preserve parent-class expectations in subclasses; keep interfaces narrow; and make high-level policy depend on abstractions rather than low-level details. These principles reduce entanglement, but applying them mechanically can make a small program needlessly elaborate.
Composition is especially powerful when variation has multiple independent dimensions. It turns a growing inheritance tree into pieces that can be combined, while runtime replacement makes the design more adaptable. Yet inheritance is not inherently a mistake: a stable, genuine subtype relationship can be clearer than a network of delegated objects. The useful question is whether a subclass can honor what clients expect from its parent, and whether its variations really belong together. Design principles guide that judgment; they do not eliminate it.
Choose creation patterns by what makes construction unstable
Separate creation from use. Five creational patterns solve different construction problems. Factory Method lets subclasses choose a product behind a common interface, as road and sea logistics choose trucks or ships. Abstract Factory produces compatible families, such as furniture pieces in one style. Builder assembles a complex object in optional steps, avoiding constructors crowded with unused settings; a director can reuse construction sequences. Prototype copies a configured object when rebuilding it would be cumbersome. Singleton restricts a class to one shared instance, such as a database connection.
Flexibility has a bill. Factories can isolate product choices; builders can separate complicated assembly; prototypes can replace many configuration subclasses. A singleton offers global access, but can make dependencies less visible and tests harder. Each pattern adds structure, so it earns its place only when construction complexity, variation, or resource reuse justifies that cost.
These patterns are easier to distinguish by the unstable part they isolate. Is the product type unknown, are several products required to match, are there many construction steps, or is a configured object better copied? Those questions point to different designs. The Singleton example also exposes a tradeoff: convenience can conceal who depends on a shared resource. Centralized construction is valuable when it contains real variation, but it should not become a reflexive wrapper around every constructor.
Match structural patterns to the boundary you need to reshape
Change the relationship, not the whole system. Structural patterns reshape how objects connect. Adapter translates an incompatible interface, like XML data presented to a JSON-only library. Bridge splits independent dimensions, such as shape and color, into separate hierarchies. Composite lets leaves and nested containers share an interface, so an order can total products inside boxes recursively. Decorator wraps an object with optional behavior, such as adding encryption or compression to file storage. Facade offers a simpler entry to a complicated library. Flyweight shares repeated, immutable data among many objects to save memory. Proxy keeps the same interface while controlling access, for example through caching or delayed creation.
Ask what the wrapper changes. Adapter changes the interface; Decorator adds behavior; Proxy controls access; Facade simplifies a subsystem. These distinctions matter because similar-looking wrappers solve different problems. Flyweight is specifically a memory optimization, not a general technique for making objects lighter.
The patterns form a useful map of boundaries: translate, split, nest, enhance, simplify, share, or control. In practice, the distinctions prevent a common design error: choosing a familiar wrapper shape while overlooking its intent. Flyweight deserves particular caution because moving state out of objects increases bookkeeping and can trade memory use for computation. Likewise, a facade can become a catch-all coordinator. A structural pattern improves a system only when the new boundary is simpler than the one it replaces.
Route requests and events through objects with clear roles
Make communication explicit. Chain of Responsibility passes a request through handlers that can process it or stop it, as with ordered authentication and validation checks. Command packages a request as an object, letting a button trigger an operation that can be queued, reused, or undone. Iterator separates traversal from a collection's internal structure. Mediator moves coordination among tightly connected components into one coordinator, as a dialog can manage form controls. Observer lets interested subscribers register for a publisher's events, instead of repeatedly checking whether something changed.
Protect state while keeping history. Memento lets an object create a snapshot of its own private state, while a caretaker stores snapshots and requests restoration. In a text editor, this supports undo without requiring the history manager to inspect the editor's internals. These patterns separate who initiates, processes, coordinates, observes, or remembers an operation.
These designs are different answers to a deceptively broad question: how should one object reach another? A chain allows successive handlers; a command records a specific request; an observer broadcasts updates; a mediator centralizes coordination. Memento adds a different concern, preserving state without opening it to outsiders. Clear roles can make dependencies easier to reason about, though centralization has limits: a mediator that knows every detail can become as tangled as the components it was meant to untangle.
Separate algorithm choice, object state, and fixed process skeletons
Identify what varies. Strategy puts interchangeable algorithms behind one interface; a route planner can switch among driving, walking, or transit routes. State gives each state its own behavior and transitions, replacing sprawling conditionals in a document or media player. Template Method fixes an algorithm's overall sequence but lets subclasses supply or adjust particular steps, as document parsers share analysis while handling file formats differently.
Add operations without scattering them. Visitor moves an operation across a class hierarchy into a separate visitor. Geographic nodes can accept an XML exporter, which then handles cities and industries differently through double dispatch: each node directs the visitor to the method matching its own type. Visitor helps when operations change more often than element classes, but adding a new element type requires updating visitors.
Strategy, State, and Template Method all organize variation, but they locate control differently: the client chooses an algorithm, the object's current condition determines its behavior, or a superclass preserves the process sequence. Visitor makes a different bargain, keeping new operations outside stable data classes at the cost of making the element hierarchy harder to extend. These are not merely stylistic alternatives. The expected direction of change, whether new behaviors or new object types, should determine which side bears the adaptation cost.
Pick patterns by intent, then stop before flexibility becomes scaffolding
Start with the pressure in the code. Is a conditional growing because an algorithm changes? Consider Strategy. Are product combinations multiplying? Consider Abstract Factory or Bridge, depending on whether the variation concerns object families or independent dimensions. Is a third-party interface incompatible? Consider Adapter. Does the client need a simpler entrance to many subsystem classes? Consider Facade. These patterns may share structures, but their purpose is the deciding factor.
Treat patterns as a middle layer of reuse. Classes reuse implementation, frameworks impose broader reusable structures, and patterns share design relationships without requiring a framework. The book repeatedly warns that flexibility can increase complexity. A short, stable program may need no pattern; a mature component facing repeated change may benefit from one. Prefer the smallest design that contains the change without burdening every user.
The strongest practical lesson is to use patterns as diagnostic language, not as a checklist. A pattern is useful when it localizes a change, clarifies responsibilities, or gives a team a shared model. It is less useful when the anticipated variation never arrives or when the resulting abstractions make the ordinary path harder to follow. This is a form of design economy: spend complexity where it buys resilience. The book's own cautions make pragmatism part of the method, not an exception to it.
Analysis
The book's real subject is not 22 isolated patterns. It is the management of change through object relationships. Each pattern offers a way to move a source of volatility: a construction choice moves into a factory, an algorithm into a strategy, state-specific behavior into state objects, and communication into a mediator or subscription mechanism. The catalog becomes more coherent when read as a set of answers to one question: which component should know about this decision?
That perspective also explains the book's recurring preference for interfaces and composition. An interface narrows what collaborators need to know; composition lets responsibilities vary independently. Both techniques reduce the number of places a change can reach. Their cost is additional indirection, and indirection is not free. Every new abstraction asks a reader to follow another reference, infer ownership, and understand a wider set of types. A design can therefore be locally flexible but globally harder to comprehend.
The most useful standard is not whether a design resembles a named pattern. It is whether likely changes become easier to make and verify without forcing unrelated code to move. That standard makes the cautions around Singleton, Flyweight, Visitor, and elaborate interfaces especially important. Singleton hides dependencies behind global access; Flyweight reorganizes state for a measured memory problem; Visitor favors new operations over new element types; and broad abstractions can impose costs on clients that need only a small capability.
The book's pseudocode and examples make the catalog accessible across languages, while also reflecting its object-oriented emphasis. Modern languages may express some strategies as functions, and other architectural styles may handle coordination without these class structures. The transferable insight is broader than the diagrams: isolate decisions that change for different reasons, preserve clear contracts, and accept complexity only when it buys a concrete form of changeability.
People Also Read
Glossary
Creational design patterns
Object construction structuresA family of design patterns that separates object creation from the code that uses the objects. Factory Method, Abstract Factory, Builder, Prototype, and Singleton address different pressures, including variable product types, matching product families, complex setup, copying configured objects, and restricting instance count.
Structural design patterns
Object arrangement structuresA family of patterns for assembling classes and objects into larger arrangements while preserving flexibility. Adapter, Bridge, Composite, Decorator, Facade, Flyweight, and Proxy reshape interfaces, dimensions, trees, behavior layers, subsystem access, shared state, or service access.
Behavioral design patterns
Interaction and responsibility structuresA family of patterns concerned with communication, algorithms, and assigning work among objects. The book's examples include request chains, commands, iterators, mediators, snapshots, subscriptions, state objects, strategies, template algorithms, and visitors.
SOLID principles
Five maintainability guidelinesA mnemonic for five object-oriented design principles: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. They encourage cohesive classes, safe extension, compatible subtypes, narrow interfaces, and abstractions that separate high-level policy from low-level details.
Factory Method
Subclass-selected product creationA creation pattern in which a superclass declares a method for producing a product, while subclasses can choose the concrete product type. Client code uses the common product interface rather than depending directly on each concrete class.
Abstract Factory
Creation of compatible product familiesA creation pattern that offers methods for producing several related product types without exposing their concrete classes. A concrete factory represents one variant and creates products that are designed to work together, such as matching interface controls or furniture styles.
Builder
Stepwise complex constructionA creation pattern that moves complex object setup into a builder with separate construction steps. Different builders can use the same sequence to produce different representations. An optional director stores reusable sequences, while the client retrieves the completed result from the builder.
Prototype
Copying configured objectsA creation pattern in which an object supplies its own cloning operation through a shared interface. Clients can copy a configured object without knowing its concrete class, reducing repeated setup or the need for subclasses that differ only by initial configuration.
Singleton
One shared class instanceA creation pattern that restricts a class to a single instance and provides a global way to access it. A private constructor and a static access method commonly enforce the restriction. The pattern can complicate testing and hide dependencies between components.
Adapter
Interface translation wrapperA structural pattern that lets otherwise incompatible objects collaborate. The adapter implements the interface expected by a client, wraps a service object, and translates calls or data into the format the service understands.
Bridge
Independent variation hierarchiesA structural pattern that separates two dimensions of variation into distinct hierarchies linked through composition. For example, shapes can delegate color behavior to color objects, so adding a color does not require a subclass for every shape.
Composite
Uniform tree structuresA structural pattern that gives individual objects and containers a common interface. Containers can hold leaves and other containers, then delegate work recursively. Clients can operate on a whole tree, such as nested boxes of products, without inspecting each concrete type.
Decorator
Composable behavior wrapperA structural pattern that wraps an object with another object implementing the same interface, adding behavior before or after delegated calls. Multiple decorators can be layered at runtime, such as compression and encryption around a file data source.
Facade
Simplified subsystem interfaceA structural pattern that provides a limited, convenient interface to a complex library or subsystem. The facade coordinates underlying classes while clients use a simpler entry point. It can reduce client coupling, but an oversized facade can become a central, overburdened object.
Flyweight
Shared immutable object stateA memory-saving pattern that extracts repeated, stable data into shared objects called flyweights. Unique contextual data remains outside them. In a game, many particles can share a sprite and color while retaining separate positions and movement details.
Proxy
Controlled service accessA structural pattern whose proxy implements the same interface as a service and controls access to it. A proxy can delay creation, cache results, check permissions, log calls, or represent a remote service while remaining usable by ordinary clients.
Chain of Responsibility
Sequential request handlingA behavioral pattern that links handlers so a request can pass from one to another. Each handler decides whether to process the request, forward it, or stop the chain. The approach supports configurable sequences, though some requests may remain unhandled.
Command
Request packaged as an objectA behavioral pattern that represents an operation as an object containing the information needed to execute it. A sender can trigger the command without knowing the receiver's details. Commands can be queued, reused by multiple controls, logged, or combined with history for undo.
Iterator
Encapsulated collection traversalA behavioral pattern that moves traversal logic into a separate object. An iterator tracks its own position and presents a common way to visit elements without exposing how the collection stores them. Different iterators can support different traversal methods.
Mediator
Centralized component coordinationA behavioral pattern that prevents a group of components from communicating directly with one another. Components notify a mediator, which decides how to coordinate them. This can reduce mutual dependencies, but a mediator that accumulates every responsibility can become difficult to maintain.
Memento
Encapsulated state snapshotA behavioral pattern in which an object creates a snapshot of its own state and can later restore itself from it. A caretaker stores snapshots but has limited access to their contents, allowing undo or rollback without exposing the originator's private state.
Observer
Dynamic event subscriptionsA behavioral pattern in which a publisher keeps a list of subscribers and notifies them when relevant events occur. Subscribers can register or leave dynamically, allowing interested objects to react without requiring the publisher to depend on their concrete classes.
State
State-specific object behaviorA behavioral pattern that gives an object's possible states separate classes. The context delegates behavior to its current state object, and transitions replace that object. This can replace sprawling conditionals when behavior changes significantly with state.
Strategy
Interchangeable algorithmsA behavioral pattern that places variants of an algorithm behind a shared interface. A context delegates the relevant work to a strategy supplied by its client, which can change the chosen algorithm without changing the context's core logic.
Template Method
Fixed algorithm, variable stepsA behavioral pattern that defines an algorithm's sequence in a superclass while allowing subclasses to implement or customize individual steps. Shared processing can remain in the base class; format-specific operations can vary in subclasses.
Visitor
External operations on object typesA behavioral pattern that places operations in visitor objects instead of embedding each operation in the elements it affects. Elements accept a visitor and direct it to the method for their concrete type through double dispatch. New element types require visitor updates.
Intrinisc state
Shared stable object dataIn Flyweight, intrinsic state is the stable portion of an object's data that can be shared among many instances. A particle's color or sprite may be intrinsic when those values are identical across many particles. Flyweights should not expose changes to shared state.
Extrinsic state
Context-specific object dataIn Flyweight, extrinsic state is the data that differs by object or context and therefore stays outside the shared flyweight. Coordinates and movement values for individual particles are examples. This information is supplied when the flyweight performs work or stored in a separate context object.
Double Dispatch
Type-directed visitor selectionA technique used by Visitor in which the element first accepts a visitor, then calls the visitor method corresponding to its own concrete type. This lets the program select behavior based on both the visitor and element types without a client-side chain of type checks.
Download PDF
Download EPUB
.epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.