Key Takeaways
Name recurring design problems so teams can reuse judgment, not just code
Patterns preserve hard-won choices. Experienced designers do not solve every problem from scratch. They recognize recurring situations and reuse arrangements that have worked before. A design pattern records such an arrangement in a form others can understand and adapt. The book presents 23 patterns gathered from repeated use in object-oriented systems, not speculative tricks or ready-made chunks of code.
A pattern explains its trade-offs. It identifies the problem and context, describes the participating objects and their relationships, and explains when the approach fits and what it costs. Naming a pattern gives a team shorthand for discussing a design. The name is useful only when everyone understands the problem it addresses and the trade-offs behind it.
A pattern name works like a compact model: it lets a team discuss a whole family of design decisions without redrawing every class relationship. That shared vocabulary can make architectural reasoning faster and expose assumptions that might otherwise remain tacit. The compression has a risk, though. A label can sound like a verdict, encouraging people to stop asking whether the problem actually matches. The strongest use of a pattern name is as the beginning of a design conversation, not its conclusion.
Make dependencies point to interfaces, not concrete classes
Clients need contracts, not internals. An interface describes the requests an object can handle, while its class determines how those requests are implemented. If client code depends on a particular concrete class, changing that implementation can force changes throughout the system. If it depends on an interface instead, another object can take its place as long as it honors the same contract.
Creation is a common leak. A client that directly constructs a platform-specific button has committed to that platform. Creational patterns such as Abstract Factory and Factory Method move that choice behind a separate creation mechanism. The application can then work with an abstract widget or product interface while a factory selects the concrete class. This is the book's central design principle: program to an interface rather than an implementation.
This principle is a form of dependency control. A stable interface acts as a boundary across which implementation changes can be contained, much like a carefully defined protocol between organizations. Its value depends on the interface remaining meaningful: an abstraction with too many special cases can merely hide coupling rather than remove it. The practical question is not whether every class needs an interface, but whether a likely change should be allowed to cross this boundary.
Compose behaviors at runtime before multiplying subclasses
Inheritance fixes choices early. A subclass inherits implementation from a parent, which is convenient but can bind a design to details the subclass should not need. If every combination of features gets its own subclass, class counts grow quickly. A bordered, scrollable text view, for instance, can require separate classes for each combination of border and scrolling behavior.
Composition keeps parts replaceable. Object composition builds behavior by connecting objects through interfaces. A window can contain a shape and delegate shape-related work to it, rather than being a kind of shape itself. The contained object can be replaced at runtime if another object supports the same interface. This approach tends to preserve encapsulation and make classes more focused, though many interacting objects can be harder to follow and may add runtime indirection.
The choice resembles a broader engineering trade-off between static structure and runtime configurability. Composition makes variation local and reversible, which is valuable when requirements genuinely change. But flexibility is not free: each delegation adds a relationship readers must trace, and a design can become an intricate web of tiny objects. The useful test is whether the expected variation outweighs the explanatory cost. Stable behavior often benefits from simpler inheritance or direct calls.
Choose a creation pattern by what you need to vary
Five patterns hide construction choices. Abstract Factory creates related product families, such as a matching set of interface widgets. Builder separates the steps for constructing a complex object from the form it takes. Factory Method lets subclasses choose which product class to instantiate. Prototype creates products by copying example objects. Singleton controls access to a single instance.
Their flexibility differs. In a maze game, a factory can produce rooms, walls, and doors of one consistent kind; a builder can assemble different maze representations step by step; and a prototype factory can clone different component examples. Factory Method is often simpler at first, while object-based factories and prototypes offer more ways to vary construction. Each adds structure, so use one when the class choice or construction process is expected to change.
These patterns separate two decisions that are often tangled: what should be created, and who should decide how it is created. That distinction helps identify the smallest useful abstraction. A family-wide factory is valuable when products must remain compatible, while a builder earns its complexity when construction has meaningful stages. A singleton is the most restrictive choice and deserves particular scrutiny, because convenient global access can also create hidden dependencies.
Build trees once, then treat leaves and groups alike
Composite turns hierarchy into a uniform interface. It represents a part-whole structure as a tree whose simple elements and groups share a common interface. In the document editor Lexi, characters, images, rows, and columns are all glyphs. A row can draw its children, while a character draws itself. Client code can work with either without continually checking whether it has encountered a primitive or a group.
Sharing controls the cost. Fine-grained objects can make a design flexible but consume substantial memory. Flyweight reduces duplication by sharing objects that contain context-independent information, while passing context-dependent details, such as position, when needed. In the Doc editor example, a document with 180,000 characters used only 480 character objects. Sharing is unsuitable when identity matters or most state is unique to each occurrence.
Composite captures a useful symmetry: a group can participate in the same operations as its parts, so complexity can grow without forcing every client to understand the tree. Flyweight addresses the corresponding cost of making everything an object. Together they show that abstraction and efficiency need not be opposites, provided shared state is separated cleanly from local context. The boundary can be delicate: once context is externalized, callers must reliably supply it.
Match the structural pattern to the boundary you need
Similar wrappers solve different problems. Adapter translates an existing class's interface into the one a client expects, as when a text-view toolkit class is made usable as a drawing-editor shape. Bridge separates an abstraction from its platform-specific implementation so both sides can evolve. Decorator keeps the component's interface but adds responsibilities around it, such as borders or scrolling. Proxy keeps a similar interface while controlling access, perhaps loading a large image only when it must be drawn.
Facade simplifies a subsystem. It gives ordinary clients a higher-level entry point to a collection of detailed classes, as a compiler object can coordinate scanning, parsing, and code generation. These patterns all add indirection, but for distinct reasons: translate, vary, embellish, control, or simplify. Choosing by purpose prevents a familiar structure from being mistaken for the right solution.
The distinctions matter because structural similarity can mislead. A proxy and decorator may both forward calls, yet one governs access while the other extends behavior. An adapter repairs a mismatch that already exists; a bridge anticipates independent variation. This is a useful reminder that architecture is about intent as much as diagrams. Indirection is justified when it protects a specific boundary, not simply because a pattern catalog offers a name for it.
Move changing algorithms and states out of sprawling conditionals
Strategy makes algorithms interchangeable. Lexi delegates line breaking to a compositor, so a quick layout method or a more elaborate method can format the same document without changing its glyphs. Template Method takes another route: a parent class fixes the order of an algorithm's steps, while subclasses fill in selected steps. Strategy delegates the algorithm; Template Method varies parts of an inherited procedure.
State makes behavior follow an object. A network connection can delegate requests to an object representing its current condition, such as open or closed, instead of repeating state checks across many methods. Interpreter represents a small language's grammar as expression classes and evaluates a syntax tree through them. This can work neatly for simple grammars, but a large grammar creates many classes and may be better served by parser-generation tools.
These patterns convert hidden branches into explicit design choices. That can make change easier to localize and make behavior more legible to maintainers. The trade-off is that classes and objects multiply, and the decision logic does not disappear so much as move. Strategy is strongest when clients need to select among algorithms; State fits behavior tied to a changing lifecycle; Template Method suits a stable sequence with a few variable steps.
Decouple collaborators by choosing how requests travel
Observer broadcasts changes. A subject notifies registered observers when its state changes, allowing, for example, a spreadsheet and a chart to reflect the same underlying data without referring to each other. Mediator instead coordinates a group of colleagues through a central object. In a dialog box, a director can react to a list selection by updating a text field and enabling buttons.
Chain of Responsibility searches for a handler. A request passes through candidate objects until one handles it. A help request can move from a button to its dialog and then to the application, allowing the most specific available explanation to answer. These mechanisms reduce direct dependencies, but their flows differ. Observer distributes notification, Mediator centralizes coordination, and a chain makes the eventual receiver conditional.
These are different ways to manage social complexity inside software. Observer suits many independent listeners, while Mediator makes coordination rules visible in one place. A chain is useful when responsibility depends on context or fallback. Each trades direct links for a less obvious path of control. Debugging therefore depends on documenting subscriptions, mediator rules, or chain order, rather than assuming that lower coupling automatically makes a system easier to understand.
Represent requests as objects when users need undo and redo
Command turns an action into data. A menu item can hold a command object without knowing which application object will perform the work. The same command can be attached to a button, queued, or recorded. To support undo, a command stores what it needs to reverse its effect; a history of commands can be traversed backward to undo and forward to redo. Commands can also be grouped into a larger command.
Memento preserves hidden state. Some operations affect internal structures that cannot be reliably reconstructed by simply applying an opposite action. In a drawing editor, moving a connected shape can cause a constraint solver to rearrange other objects. A memento stores a private snapshot that the solver itself can restore, without exposing its internals to the undo system. Snapshots can be costly, so the saved state should be no larger than the task requires.
Command makes action history explicit, a foundation for undo, auditing, and deferred execution. Memento complements it when reversal requires restoring more than an obvious inverse operation. Together they distinguish the record of an operation from the protected state needed to restore its effects. This design also reveals a product decision: undo is not merely a button. It requires defining which actions count, what state must survive, and how reliably restoration must work.
Separate traversal from operations when structures stay stable
Iterator hides the route through data. It lets clients visit elements sequentially without knowing whether a collection uses an array, a linked list, or another representation. Its own position allows multiple traversals of the same structure at once. Different iterators can support different orders, though modifying a collection during traversal requires care.
Visitor separates operations from elements. In a compiler, a visitor can perform type checking or code generation across syntax-tree nodes without placing every operation inside every node class. This works best when the node structure is relatively stable and new operations are common. The cost appears when a new node class is added: every visitor interface may need a corresponding visit operation. Iterator abstracts how elements are reached; Visitor organizes what to do with them.
The two patterns address separate axes of change. Iterator protects clients from changes in collection representation, while Visitor protects element classes from accumulating unrelated operations. Their limits follow from those choices: iteration can become fragile under concurrent structural changes, and visitors make expanding the element taxonomy expensive. The design question is which side changes more often. Choosing the stable side as the foundation keeps the other side more adaptable.
Use Lexi's eight-pattern editor as a map, not a blueprint
One editor makes the catalog concrete. Lexi is a fictional WYSIWYG document editor whose design problems include representing nested text and graphics, formatting lines, supporting different interface styles and window systems, and implementing undoable user actions. Its document is a Composite of glyphs; formatting uses Strategy; borders and scrolling use Decorator; widget families use Abstract Factory; and platform-specific windows use Bridge.
Analysis adds two more patterns. Iterator traverses the glyph structure without exposing its storage, while Visitor supports spelling checks and hyphenation without loading those operations into every glyph class. Together, the eight patterns keep distinct sources of change apart. The lesson is not to install all eight by default. First identify likely changes, then check each pattern's applicability and consequences. Flexibility is useful when the requirement arrives, not merely because it is available.
Lexi's value lies in showing patterns cooperating around one application, rather than presenting 23 isolated definitions. Each pattern protects a different seam, and those seams collectively make the editor easier to extend. This resembles layered system design: local decisions become safer when neighboring parts communicate through deliberate contracts. Yet every seam adds concepts for a maintainer to learn. The case study therefore supports both modularity and restraint, especially when a requirement is unlikely to change.
Analysis
The book's lasting contribution is less a set of object-oriented recipes than a way to reason about change. Its patterns ask designers to identify what is unstable, give that variation a boundary, and make neighboring code depend on the boundary rather than the volatile implementation. This makes the catalog a practical theory of modularity: each pattern proposes a particular allocation of responsibility, with an explicit price in indirection, classes, or complexity.
The three-part classification, creational, structural, and behavioral, is useful as an initial search map, but it is not a complete explanation of a pattern. The deeper organizing question is what must vary independently. Abstract Factory handles product-family selection; Bridge separates an interface from an implementation; Observer addresses one-to-many state notification. The same architectural aim, reducing unnecessary dependencies, appears in different forms because the underlying problems differ.
The Lexi case study is especially effective because it turns the catalog into a design narrative. Its document structure, formatting, user interface, platform support, commands, and text analysis each create a different pressure. The patterns are not decorations added after the fact; they are answers to specific pressures. At the same time, the book warns that flexibility can make software harder to understand. That warning prevents its central principle from collapsing into abstraction for abstraction's sake.
The patterns are rooted in the object-oriented languages and systems of their time. Some mechanisms can be expressed differently when a language directly supports closures, generics, or richer dispatch. That does not erase the underlying design questions, but it does mean the pattern name should not dictate the implementation. The most durable practice is to study the problem, compare trade-offs, and use the smallest structure that protects a likely change.
Review Summary
Design Patterns is widely regarded as a seminal work in software engineering, introducing the concept of design patterns to improve code reusability and maintainability. While some readers find it dry and outdated, many praise its comprehensive catalog of patterns and their applications. The book is considered essential reading for object-oriented programmers, offering valuable insights into solving common design problems. Critics note that some patterns may be less relevant in modern languages, but the overall principles remain important. The book's impact on software development practices is widely acknowledged.
People Also Read
Glossary
Design pattern
Reusable design solutionA design pattern describes a recurring object-oriented design problem, the general arrangement of objects and classes used to address it, and the consequences of choosing that arrangement. It is not finished code to copy unchanged. Designers adapt it to a particular context, language, and set of constraints.
Programming to an Interface, not an Implementation
Depend on behavior contractsA design principle that tells clients to rely on an object's supported operations rather than its concrete class or internal implementation. Different classes can then serve the same client if they honor the same interface. This reduces implementation dependencies and makes substitution easier.
Object composition
Combine collaborating objectsA reuse technique that assembles objects with defined interfaces to create more complex behavior. Unlike inheritance, which fixes class relationships at compile time, composition can connect or replace objects at runtime. It tends to preserve encapsulation, but the resulting network of relationships can be harder to understand.
Abstract Factory
Create compatible product familiesA creational pattern that provides an interface for producing related objects without naming their concrete classes. A client selects a concrete factory, which creates a consistent family, such as widgets that share one visual style. Adding an entirely new product type may require changing the factory interface and its implementations.
Composite
Unify parts and groupsA structural pattern for representing part-whole hierarchies as trees. Primitive objects and groups share a common interface, allowing clients to handle either uniformly. A composite usually forwards operations to its children. This simplifies clients but can make it difficult to restrict which child types a group accepts.
Decorator
Add responsibilities through wrappingA structural pattern that surrounds an object with another object sharing its interface. The wrapper forwards requests and can add behavior before or after forwarding. Decorators can be nested or removed at runtime, providing an alternative to subclasses for optional features such as borders or scrolling.
Bridge
Separate abstraction and implementationA structural pattern that divides an abstraction from its implementation into separate class hierarchies connected through composition. The abstraction presents the interface clients use, while the implementation supplies lower-level, often platform-specific operations. Either hierarchy can be extended without multiplying subclasses across both.
Strategy
Make algorithms interchangeableA behavioral pattern that places each algorithm in a separate object behind a shared interface. A context delegates the relevant work to its selected strategy. This lets algorithms vary independently from the clients that use them, and can replace long conditional branches, at the cost of additional objects and selection decisions.
Command
Represent a request as an objectA behavioral pattern that packages a request so it can be passed, stored, queued, logged, or executed later. A command can connect an invoking object, such as a menu item, with a receiver that knows how to perform the action. Additional state and reversal operations can support undo and redo.
Memento
Save restorable private stateA behavioral pattern that stores a snapshot of an object's state without making that object's internal representation public. The object that creates the memento is responsible for reading and restoring its contents; another object can keep the snapshot and return it when needed. Copying large states can be expensive.
Observer
Notify dependent objectsA behavioral pattern that establishes a one-to-many relationship between a subject and its observers. When the subject changes, it notifies observers, which can update themselves using information from the subject. This supports independent views of shared data without requiring the subject to know their concrete classes.
Iterator
Traverse without exposing storageA behavioral pattern that provides a separate object for accessing elements in sequence. The iterator tracks its own position, while the aggregate hides its internal representation. Different iterators can support different traversal orders, and multiple traversals can proceed independently.
Visitor
Add operations to stable structuresA behavioral pattern that places operations on an object structure in separate visitor objects. Each element accepts a visitor and dispatches to the operation appropriate to its class. This makes new operations easier to add when the element classes are stable, but adding a new element class often requires updating every visitor.
Flyweight
Share objects to save memoryA structural pattern that reduces the cost of many fine-grained objects by sharing instances. Each shared object stores intrinsic state that does not depend on where it is used; clients supply extrinsic, context-dependent state when making requests. The approach saves storage but can add lookup and state-passing costs.
FAQ
1. What is Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma about?
- Comprehensive design pattern catalog: The book systematically names, explains, and motivates 23 general design patterns that address recurring problems in object-oriented software development.
- Focus on object-oriented design: It emphasizes how to use objects, inheritance, and polymorphism to create flexible, reusable, and maintainable software architectures.
- Reusable solutions: Patterns are presented as proven, general arrangements of classes and objects that can be customized to solve specific design problems in various contexts.
- Practical examples and case studies: The book includes real-world examples and a case study (Lexi editor) to illustrate how patterns are applied in practice.
2. Why should I read Design Patterns by Erich Gamma and others?
- Shared design vocabulary: The book provides a common language for software designers, making it easier to communicate, document, and discuss complex system designs.
- Expert knowledge transfer: It captures and distills expert design experience, helping both novices and experienced programmers improve their design skills more rapidly.
- Facilitates software reuse and refactoring: The patterns guide the creation of reusable software components and serve as targets for refactoring, supporting software evolution.
- Widely acclaimed resource: The book is praised for its clarity, practical value, and lasting impact on the field of software engineering.
3. What are the key takeaways from Design Patterns: Elements of Reusable Object-Oriented Software?
- Patterns as reusable solutions: Design patterns provide elegant, time-tested solutions to common design problems, promoting code reuse and flexibility.
- Three main pattern categories: Patterns are organized into Creational, Structural, and Behavioral types, each addressing different aspects of software design.
- Design for change: The book emphasizes designing systems that are easy to extend and maintain by encapsulating variability and reducing coupling.
- Principles over recipes: Rather than offering rigid templates, the book teaches principles and trade-offs, encouraging thoughtful application of patterns.
4. What are design patterns according to Design Patterns by Erich Gamma et al.?
- Definition and purpose: A design pattern describes a recurring problem in a context and the core of its solution, enabling repeated use without duplication.
- Four essential elements: Each pattern includes a name, a problem description, a solution outline (abstract, not concrete), and consequences (trade-offs and results).
- Capturing design experience: Patterns distill key aspects of successful designs, including class roles, collaborations, and responsibilities, to facilitate reusable object-oriented design.
5. How are design patterns organized in Design Patterns: Elements of Reusable Object-Oriented Software?
- Three main categories: Patterns are classified as Creational (object creation), Structural (class/object composition), and Behavioral (object communication).
- Class vs. object scope: Patterns are further distinguished by whether they apply to classes (static, compile-time) or objects (dynamic, run-time).
- Interrelated catalog: The book provides cross-references and diagrams to show how patterns relate, combine, or serve as alternatives to each other.
6. What are the main Creational, Structural, and Behavioral patterns in Design Patterns by Erich Gamma?
- Creational patterns: Abstract Factory, Builder, Factory Method, Prototype, and Singleton focus on object creation mechanisms.
- Structural patterns: Adapter, Bridge, Composite, Decorator, Facade, Flyweight, and Proxy address class and object composition.
- Behavioral patterns: Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, and Visitor focus on communication and responsibility among objects.
- Purpose of categories: Each category addresses a different set of recurring design challenges in object-oriented software.
7. What is the principle of "program to an interface, not an implementation" in Design Patterns by Erich Gamma?
- Interface over implementation: Clients should depend on abstract interfaces (often defined by abstract classes) rather than concrete implementations to maximize flexibility.
- Enables polymorphism: This principle allows objects of different classes to be used interchangeably if they share the same interface.
- Supports decoupling: It reduces dependencies between components, making systems easier to extend and modify.
- Creational pattern support: Patterns like Abstract Factory and Factory Method help instantiate objects without binding clients to specific classes.
8. How do inheritance and composition differ as reuse mechanisms in Design Patterns by Erich Gamma?
- Inheritance (white-box reuse): Shares implementation via subclassing but exposes subclass to parent class internals, which can break encapsulation and limit flexibility.
- Composition (black-box reuse): Assembles objects dynamically through well-defined interfaces, preserving encapsulation and allowing behavior to vary at run-time.
- Design recommendation: The book advocates favoring object composition over class inheritance to keep designs flexible, focused, and reusable.
- Pattern examples: Many patterns, such as Decorator and Strategy, leverage composition for greater adaptability.
9. How does delegation work in Design Patterns: Elements of Reusable Object-Oriented Software and which patterns use it?
- Delegation concept: An object handles a request by delegating it to another object, similar to how subclasses defer to parent classes in inheritance.
- Enables dynamic behavior: Delegation allows for dynamic composition of behavior at run-time, increasing flexibility.
- Pattern usage: Key patterns using delegation include State, Strategy, Visitor, Mediator, Chain of Responsibility, and Bridge.
- Benefits: Delegation supports encapsulation and makes it easier to change or extend object behavior without modifying existing code.
10. How does Design Patterns by Erich Gamma illustrate the use of patterns in a real application?
- Lexi case study: The book presents Lexi, a WYSIWYG document editor, as a comprehensive example of pattern application.
- Multiple patterns in action: Patterns such as Composite, Strategy, Decorator, Abstract Factory, Bridge, Command, Iterator, and Visitor are used to solve practical design problems.
- Demonstrates pattern interaction: The case study shows how patterns can be combined and interact within a complex system.
- Learning by example: This real-world scenario helps readers understand the practical value and implementation of design patterns.
11. What are some key Structural patterns in Design Patterns by Erich Gamma, and how do they work?
- Decorator: Adds responsibilities to objects dynamically by wrapping them, avoiding subclass explosion and enabling flexible feature combinations.
- Facade: Provides a unified, simplified interface to a complex subsystem, reducing dependencies and making systems easier to use.
- Flyweight: Shares fine-grained objects efficiently by separating intrinsic (shared) and extrinsic (context-dependent) state, reducing memory usage.
- Proxy: Acts as a surrogate or placeholder for another object, controlling access, deferring creation, or adding functionality transparently.
12. How do Behavioral patterns like Observer, State, and Visitor function in Design Patterns by Erich Gamma?
- Observer: Establishes a one-to-many dependency so that when one object changes state, all its dependents are notified and updated automatically, promoting loose coupling.
- State: Encapsulates state-specific behavior in separate objects, allowing an object to change its behavior when its internal state changes, and replacing complex conditionals.
- Visitor: Separates operations from object structure, enabling new operations to be added without modifying element classes, using double dispatch for flexibility.
- Pattern trade-offs: These patterns simplify communication, state management, and operation extension, but may introduce complexity or make adding new element types harder.
Download PDF
Download EPUB
.epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.