Start free trial
Trending New Genres Authors
EnglishEnglish
EspañolSpanish
简体中文Chinese
繁體中文Chinese (Traditional)
FrançaisFrench
DeutschGerman
日本語Japanese
PortuguêsPortuguese
ItalianoItalian
한국어Korean
РусскийRussian
NederlandsDutch
العربيةArabic
PolskiPolish
हिन्दीHindi
Tiếng ViệtVietnamese
SvenskaSwedish
ΕλληνικάGreek
TürkçeTurkish
ไทยThai
ČeštinaCzech
RomânăRomanian
MagyarHungarian
УкраїнськаUkrainian
IndonesiaIndonesian
DanskDanish
SuomiFinnish
БългарскиBulgarian
עבריתHebrew
NorskNorwegian
HrvatskiCroatian
CatalàCatalan
SlovenčinaSlovak
LietuviųLithuanian
SlovenščinaSlovenian
СрпскиSerbian
EestiEstonian
LatviešuLatvian
فارسیPersian
മലയാളംMalayalam
தமிழ்Tamil
اردوUrdu
Searching...
SoBrief
Head First Design Patterns

Head First Design Patterns

Learn to spot what changes in code, then choose the design pattern that contains it.
by Eric Freeman 2004 638 pages
4.3
9k+ ratings
Listen
Immersive
V2.3
Amazon Kindle Audible
Try Full Access for 3 Days
Unlock listening & more!
Continue

Key Takeaways

Design for the changes your code is most likely to face.

Change is the real test. SimUDuck begins with a familiar shortcut: put flying behavior in a shared Duck superclass so every duck can reuse it. The shortcut makes rubber ducks fly and means every new kind of flight behavior requires more overrides. The deeper mistake is treating inheritance as automatic design wisdom instead of asking what varies and what stays stable.

Separate likely variations. Pull changing behavior into its own component, then let the rest of the system depend on a stable contract. The book’s practical rules are to encapsulate what varies, favor composition over inheritance, and program to a supertype rather than a concrete class. These are guides, not commands to abstract every line of code.

Analysis

What's striking is that the bad duck design fails through a nonlocal side effect: a small superclass edit changes behavior in classes that were never meant to fly. That is a useful way to assess architecture. The key question is not whether inheritance is elegant, but whether a change has a predictable blast radius. Abstraction has a cost, though. Designing for imagined futures can make simple code harder to read, so the likely direction of change matters more than hypothetical flexibility.

Compose behavior so changing an algorithm does not rewrite its clients.

Give behavior its own type. The redesigned ducks hold references to separate flying and quacking behaviors. A Mallard can use wing-powered flight and ordinary quacking, while a rubber duck can squeak and remain grounded. Each behavior implements a shared interface, and the Duck delegates to it instead of owning every implementation.

Swap behavior deliberately. Because the duck holds a behavior object, a model duck can be assigned rocket-powered flight while the program runs. This is the Strategy Pattern: a family of algorithms is encapsulated behind a common type, so clients can use interchangeable implementations. Composition also lets unrelated objects, such as a duck call, reuse the same quacking behavior.

Analysis

The pattern turns behavior into a replaceable dependency, a powerful shift from classifying objects by what they are to assembling them from what they do. That makes runtime variation straightforward and supports reuse beyond the original hierarchy. The tradeoff is extra objects and indirection. If an algorithm is stable and trivial, a strategy class may be ceremony rather than flexibility. The design earns its keep when behavior genuinely varies independently of the clients that invoke it.

Let interested objects subscribe without making the subject know their identities.

One source, many listeners. In the weather station, WeatherData owns temperature, humidity, and pressure. Display objects register as observers, and WeatherData notifies them when measurements change. A current-conditions display, a statistics display, and a forecast display can respond differently to the same update. New displays can join or unsubscribe without changing the subject’s implementation.

Keep the message contract small. The Observer Pattern defines a one-to-many dependency: when a subject changes, its dependents are notified. The example first pushes all measurements to every display, then considers a pull design in which observers use getters to retrieve what they need. Push is direct; pull can reduce needless data and changes when the subject gains new fields.

Analysis

This is a design for extension through registration rather than modification. It appears in interfaces such as button listeners because an event source need not know what every listener does. The push-versus-pull choice also exposes a broader API question: should a producer decide what consumers need, or should each consumer select its own view of the state? Neither is universally best. Ordering, event volume, and consistency expectations must be explicit in real systems.

Add responsibilities by wrapping objects, not multiplying subclasses.

Build orders from layers. Starbuzz’s first approach creates a separate class for each beverage and condiment combination. With multiple bases and toppings, the class list balloons, while price changes must be repeated. The Decorator Pattern instead wraps a beverage with condiment objects. A Dark Roast can be wrapped by Mocha twice and then Whip, with each layer adding its description and cost before delegating inward.

Preserve the component type. Decorators share the interface of the objects they wrap, so a decorated beverage can still be treated as a beverage. Java I/O uses the same idea when buffering or decompressing streams. The costs are many small classes, more complicated construction, and possible trouble for client code that depends on a concrete class.

Analysis

Decorator is especially effective when optional features combine in many configurations, because combinations are assembled at runtime rather than enumerated in a class hierarchy. The beverage example makes the arithmetic and the structure visible. Yet transparency is conditional: a client that checks for a concrete type can break when a wrapper intervenes. This suggests a useful test before adopting decorators: clients should depend on the component contract, and construction should be centralized enough to keep wrapper chains understandable.

Centralize creation policy, from choosing product families to enforcing one instance.

Move decisions out of clients. The pizza store’s long conditional chain knows every concrete pizza, so adding a product means reopening that code. A Simple Factory places selection in one creation object. Factory Method goes further: a store subclass supplies the pizza while the superclass keeps the ordering process. Abstract Factory creates related product families, such as regional dough, sauce, and cheese, without making the pizza depend on their concrete types.

Choose the right guarantee. A Singleton controls creation when a class should have one shared instance, such as the chocolate boiler. Its classic lazy version needs care under concurrent access. Eager creation avoids that race; synchronization or double-checked locking are other options. The book also presents Java enums as a concise way to implement a Singleton.

Analysis

Factories and Singletons both make creation policy explicit, but solve different problems. Factories keep clients insulated from concrete product choices; a Singleton constrains how many instances exist. The pizza examples show that dependency direction matters as much as object construction: high-level ordering logic can rely on abstractions while regional implementations supply details. Singleton deserves more skepticism, since global access can quietly become global coupling. Restrict it to resources that truly require shared identity.

Turn requests into objects to gain undo, queues, and logs.

Separate requester from worker. A home remote has generic buttons, while vendor devices expose incompatible actions such as dimming lights, opening a garage, or setting stereo volume. A command object binds a request to the receiver that can perform it. The remote stores commands in slots and invokes a common execute method, without knowing the device-specific steps.

Make actions reusable data. A command can be queued for a worker thread, recorded for recovery, grouped into a macro, or paired with undo. Undo reverses the last action; a ceiling-fan command must remember the previous speed. A no-op command fills unused slots and removes null checks. The pattern can add classes, though lambdas can replace simple command objects when the interface has one abstract method.

Analysis

Command objects make an action portable: it can be stored, delayed, composed, or reversed. This is more than a neat remote-control trick; it separates the moment a request is made from the moment work happens. Undo also reveals an important limit: reversal requires enough state to restore the prior condition, and some effects cannot be cleanly undone. A command interface supplies structure, not magical reversibility, so each operation needs a realistic recovery policy.

Use adapters to translate interfaces, and facades to simplify them.

Translate mismatched contracts. A client written for ducks cannot call a turkey’s gobble method directly. A TurkeyAdapter implements the expected Duck interface and forwards quack requests to gobble. The client can then use the turkey without knowing the mismatch. The same idea adapts legacy Java Enumeration objects to code expecting Iterator, though removal cannot be supported and must report an unsupported operation.

Reduce a subsystem to a useful front door. The home theater requires a sequence of calls across a projector, amplifier, screen, lights, player, and popcorn maker. A facade offers a simple watch-movie operation while leaving the components available for clients needing finer control. The Principle of Least Knowledge advises objects to communicate with close collaborators rather than reaching through chains of returned objects.

Analysis

Both patterns add a layer, but their intent distinguishes them. An adapter preserves a client’s expected contract while translating another one. A facade offers a simpler route through a subsystem. The least-knowledge rule makes dependencies easier to reason about, though applying it mechanically can create layers of trivial forwarding methods. The useful question is whether the wrapper protects a real boundary or merely hides a call without reducing meaningful coupling.

Keep an algorithm's sequence fixed while subclasses fill selected steps.

Own the recipe centrally. Coffee and tea share a sequence: heat water, extract the beverage, pour it, and add condiments. The Template Method places that sequence in a superclass method, while subclasses implement the steps that differ, such as brewing coffee or steeping tea. This removes duplicated recipe logic and keeps the order consistent.

Use hooks for optional choices. A hook is a method with a default implementation that a subclass may override. The beverage example uses one to decide whether condiments should be added. In Java, sorting provides a less textbook example: Arrays controls the sort algorithm but relies on an object’s compareTo method to define ordering. The approach suits frameworks that control flow while allowing selected extensions.

Analysis

Template Method is a framework in miniature: the base class controls the procedure, and subclasses contribute bounded variation. That is useful when sequence itself is part of correctness, as in a recipe or lifecycle. The cost is inheritance-based coupling. Too many abstract steps make every subclass burdensome, while overly broad hooks make behavior hard to predict. The best template exposes only the variation points that are meaningful to the domain.

Hide collection storage behind iterators, then compose collections as trees.

Separate traversal from storage. The merged diner has one menu backed by an Array and another by an ArrayList. Without iterators, the waitress needs different loops and must know each representation. An Iterator offers a common way to check for another item and retrieve it, letting the menus preserve their storage choices while the client traverses them uniformly.

Treat nested parts as a whole. When menus gain submenus, a flat list is no longer enough. Composite structures menus and items as a tree, allowing the waitress to call print on the top-level menu and have the operation propagate through its children. Composite trades some safety for transparency: shared operations simplify clients, but a menu item may inherit operations that make no sense.

Analysis

Iterator and Composite solve neighboring but distinct problems. One hides how a collection is traversed; the other makes a hierarchy of collections and elements usable through a common interface. Together they turn a client from a manager of data structures into a user of capabilities. The design choice about unsupported operations is consequential: uniformity reduces branching, while stricter interfaces prevent invalid calls. The right balance depends on whether client simplicity or compile-time safety matters more.

Replace state-dependent conditionals with state objects that own behavior.

Make states explicit. The first gumball machine stores an integer state and repeats conditional checks in each action. Adding a winner state means editing many methods and risks inconsistent transitions. The State Pattern gives each condition its own object, such as NoQuarter, HasQuarter, Sold, and SoldOut. The machine delegates actions to its current state, and state objects handle both responses and transitions.

Pay for clarity with classes. The one-in-ten promotion adds a WinnerState that dispenses two gumballs when eligible. This is structurally similar to Strategy, but its purpose differs: a state object reflects the context’s current condition, while a strategy is generally chosen to supply an algorithm. More classes improve localization, but transitions can create dependencies among state objects.

Analysis

State objects convert branching logic into a model that mirrors the machine’s operating conditions. That can make transitions easier to inspect and extend, particularly when invalid actions have distinct responses. The gain is not free: a handful of conditions may be clearer as a small conditional than as a class hierarchy. State is most persuasive when state-specific behavior is substantial, transitions are numerous, and the current state is a meaningful part of the domain.

Put a proxy between clients and remote, costly, or protected objects.

Keep the client’s contract stable. The gumball monitor originally reads a local machine. When the CEO needs reports from distant machines, the monitor can use the same remote interface while a proxy handles lookup and network calls. Java RMI supplies much of the machinery, but the client still has to handle remote exceptions because network operations can fail.

Control access in other ways. A Virtual Proxy stands in while an expensive image loads, showing a temporary message before delegating to the image. A Protection Proxy allows or denies methods based on the caller, as in the matchmaking service where users may edit their own profile but not their own rating. Proxies share a structure with decorators, but control access rather than primarily adding responsibilities.

Analysis

Proxy is a family of boundary-management techniques. It can hide location, delay expensive work, or enforce permissions while preserving the interface expected by a client. That consistency is powerful, but transparent remote calls can conceal latency and failure if the API pretends the network is local. The RMI example acknowledges this through exceptions. A proxy should simplify access without encouraging clients to forget the operational realities it mediates.

Treat MVC as collaboration among patterns, not a template to force everywhere.

Divide application responsibilities. In Model-View-Controller, the model holds data and application logic, the view presents it, and the controller interprets user actions. The model notifies interested views when its state changes. The controller acts as a strategy for the view, while a graphical interface often forms a composite of nested components. An adapter can connect a different model to an existing view and controller.

Use patterns when they fit. The duck simulator combines factories, adapters, decorators, composites, iterators, and observers to demonstrate cooperation among patterns. The book cautions that this is an artificial workout, not a recipe for every design. Patterns communicate tested design experience, but can add classes and complexity. Begin with the simplest design that meets real requirements, then refactor when a genuine need appears.

Analysis

MVC is easiest to understand as a separation of change: interface presentation, user-input interpretation, and application state evolve at different rates. Its pattern composition is useful precisely because each pattern addresses a local relationship. Yet the label can obscure substantial differences among desktop and web implementations. The book’s warning against pattern fever is therefore essential. A pattern is a reusable design decision, not a credential, and simplicity remains a legitimate architectural achievement.

Analysis

The book’s central achievement is to teach design patterns as decisions about change, not as vocabulary to memorize. The duck simulator makes the cost of inheritance concrete: a convenient shared method causes behavior to leak into inappropriate subclasses. Each subsequent example then asks a practical question: what changes independently, who should own that change, and how much should neighboring objects know about it? This gives the patterns a coherent logic despite their variety.

Its teaching structure is itself deliberate. Familiar stories, small code fragments, exercises, diagrams, and repeated explanations create multiple routes into abstract ideas. The diner explains commands as a social workflow; pizza franchises expose factories as a way to manage regional variation; the gumball machine turns state transitions into visible behavior. The result is unusually approachable for a subject often taught as taxonomy. The limitation is that concise teaching examples can make framework mechanics appear cleaner than production systems. Distributed calls fail, collections mutate, state transitions become concurrent, and abstractions can accumulate unnecessary indirection. The book acknowledges several such costs, especially for Singleton, Decorator, Composite, and Proxy, but its examples are intentionally compact.

The most durable lesson is not that every problem has a named pattern. It is that design quality depends on placing variation at a boundary where it can be changed without disturbing unrelated code. Patterns name recurring boundary choices: delegate behavior, notify subscribers, wrap responsibilities, centralize construction, package requests, translate interfaces, or represent state explicitly. Their value is both technical and social, since a shared name compresses a design discussion. Their danger is the same compression: a familiar label can replace analysis. Used with restraint, the patterns are a vocabulary for explaining tradeoffs, not a substitute for judgment.

Summary in 30 Seconds
Good software isolates likely changes so one adjustment does not force unrelated code to change. Composition lets objects delegate behavior to interchangeable components, while observers, adapters, decorators, and proxies manage communication, mismatched interfaces, added responsibilities, and access. Factories centralize creation, commands package actions for queuing or undo, and state objects handle condition-specific behavior. Patterns clarify tradeoffs, but unnecessary abstractions add complexity.
Contains spoilers

Last updated:

Report Issue

Review Summary

4.3 out of 5
Average of 9k+ ratings from Goodreads and Amazon.

Head First Design Patterns receives overwhelmingly positive reviews for its engaging and accessible approach to teaching design patterns. Readers praise its use of humor, real-world examples, and interactive learning techniques. Many find it superior to traditional textbooks, especially for beginners. The book is commended for its clear explanations, practical examples, and emphasis on when to use patterns. Some readers note that not all patterns are covered in depth, but overall, it's highly recommended as an introduction to design patterns for programmers of various experience levels.

Your rating:
4.63
95 ratings
Want to read the full book?

Glossary

Strategy Pattern

Swappable behavior

A pattern that defines a family of algorithms, gives each algorithm its own implementation behind a common type, and lets clients use them interchangeably. A context delegates work to the selected behavior rather than hard-coding every variation. In the duck example, flight and quacking are independent behaviors that can be composed with different ducks.

Observer Pattern

One-to-many notification

A pattern that establishes a one-to-many dependency between a subject and its observers. Observers register for changes, and the subject notifies them when its state changes. The subject depends on the observer contract, not on the identities or purposes of particular observers, allowing displays or listeners to be added and removed independently.

Decorator Pattern

Runtime responsibility wrapper

A pattern that attaches responsibilities to an object by wrapping it with another object that shares its interface. A decorator can add behavior before or after delegating to the wrapped component. Multiple decorators can be layered at runtime, as in a coffee order built from a beverage and optional condiment wrappers.

Simple Factory

Centralized object selection

A commonly used programming idiom, rather than a formal GoF pattern, that moves concrete object selection into a dedicated creation method or object. Clients ask the factory for a product instead of containing repeated conditional logic and direct instantiations. It centralizes change but does not provide the subclass flexibility of Factory Method.

Factory Method Pattern

Subclass-selected creation

A pattern that declares a creation method in a creator class and lets subclasses implement it to choose the concrete product. Other creator logic can operate on the product abstraction without knowing its exact class. In the pizza store, regional subclasses choose the pizza while the shared superclass controls ordering and preparation.

Abstract Factory Pattern

Related product families

A pattern that provides an interface for creating families of related products without naming their concrete classes. Each concrete factory supplies a consistent family, such as regional pizza dough, sauce, and cheese. Clients depend on the abstract factory and product interfaces, so a family can change without rewriting the client logic.

Singleton Pattern

Single shared instance

A pattern that ensures a class has one instance and provides a global access point to it. Implementations must consider initialization and concurrency. The book compares lazy creation, synchronization, eager initialization, double-checked locking, and Java enums, while noting that global access can introduce coupling.

Command Pattern

Request as an object

A pattern that packages a request as an object, typically binding an action to the receiver that performs it. An invoker can execute commands without knowing their details. Because commands can be stored, queued, logged, grouped, or paired with undo behavior, the pattern separates when a request is made from how it is carried out.

Adapter Pattern

Interface translator

A pattern that converts one interface into another interface a client expects. The adapter implements the target contract and delegates to an object with an incompatible interface. This lets existing client code work with a new or legacy class without changing either side, as when a turkey is presented as a duck.

Facade Pattern

Simplified subsystem interface

A pattern that provides a higher-level, unified interface to a subsystem containing multiple classes or complicated interactions. A facade delegates work to the subsystem while making common tasks simpler for clients. It does not have to hide or remove the subsystem’s lower-level interfaces, which remain available when more detailed control is needed.

Template Method Pattern

Fixed algorithm skeleton

A pattern that defines the structure of an algorithm in a method while deferring selected steps to subclasses. The superclass controls the sequence; subclasses supply implementations for abstract steps and may override optional hooks. Coffee and tea share a preparation sequence while differing in brewing and condiment steps.

Iterator Pattern

Hidden collection traversal

A pattern that provides a standard way to access elements of an aggregate sequentially without exposing its internal representation. The iterator owns traversal, allowing client code to work with arrays, lists, or other collections through a common interface. This keeps collection management separate from iteration and simplifies client code.

Composite Pattern

Uniform tree structures

A pattern that composes individual objects and groups of objects into tree structures representing part-whole relationships. Clients can apply operations uniformly to leaves and composites, such as menu items and nested menus. A transparent design simplifies client code but may expose operations that do not make sense for every component.

State Pattern

State-specific behavior

A pattern that represents an object’s states as separate objects and delegates behavior to the current state. State-specific actions and transitions live in those objects instead of repeated conditional branches in the context. The gumball machine changes behavior as it moves among states such as waiting for a quarter, sold, and sold out.

Proxy Pattern

Controlled object access

A pattern that supplies a representative for another object and controls access to it. A remote proxy mediates network calls, a virtual proxy stands in while an expensive object is created, and a protection proxy restricts operations by caller. Proxies generally preserve the subject’s interface while changing how access is managed.

Model-View-Controller

Separated application roles

A compound pattern that divides an application among a model holding state and logic, a view presenting that state, and a controller interpreting user actions. The model can notify views using Observer, a controller can serve as a Strategy for a view, and a view can use Composite for nested interface elements.

Open-Closed Principle

Extend without modifying

A design principle that favors classes that can gain new behavior through extension without changing established code. It is a goal, not a demand to make every class infinitely extensible. Decorators and observers illustrate ways to add behavior or participants while leaving existing implementations unchanged.

Dependency Inversion Principle

Depend on abstractions

A design principle that advises high-level and low-level components to depend on abstractions rather than directly on each other’s concrete implementations. In the pizza example, the store and concrete pizzas both depend on the Pizza abstraction. Factories help remove direct construction dependencies, though the principle is a guideline rather than an absolute rule.

Principle of Least Knowledge

Limit direct collaborators

A design principle advising an object to communicate only with close collaborators, such as itself, parameters, created objects, and its components. Avoiding chains of calls through objects returned by other methods can reduce dependency spread. The principle can also create forwarding methods, so its value should be weighed against added complexity.

Hollywood Principle

High-level control flow

A design principle in which high-level components control the overall process and call lower-level components when their contributions are needed. Lower-level components can be plugged into the framework without controlling it or directly depending on its higher-level code. Template Method and Factory Method illustrate this arrangement.

Single Responsibility Principle

One reason to change

A design principle that says a class should have one responsibility, understood as one primary reason to change. Separating collection management from iteration can improve cohesion because changes to storage and traversal need not affect the same class. Composite illustrates a tradeoff, since a uniform interface can combine responsibilities to simplify clients.

About the Author

Eric Freeman is a computer scientist, author, and educator known for his work in software development and design patterns. He co-authored the popular "Head First" series of technical books, which use innovative teaching methods to make complex topics more accessible. Freeman's writing style is characterized by its use of humor, visual aids, and practical examples to engage readers. He has extensive experience in software engineering and has worked for major technology companies. Freeman's approach to teaching design patterns has been widely praised for its effectiveness in helping both novice and experienced programmers understand and apply these important concepts in their work.

Download PDF

To save this Head First Design Patterns summary for later, download the free PDF. You can print it out, or read offline at your convenience.
Download PDF
File size: 0.37 MB     Pages: 21

Download EPUB

To read this Head First Design Patterns summary on your e-reader device or app, download the free EPUB. The .epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.
Download EPUB
File size: 1.40 MB     Pages: 25
Want to read the full book?
Follow
Listen1 mins
Home
Swipe
Library
Get App
Try Full Access for 3 Days
Listen, bookmark, and more
Compare Features Free Pro
📖 Read Summaries
Read unlimited summaries. Free users get 3 per month
🎧 Listen to Summaries
Listen to unlimited summaries in 40 languages
—
❤️ Unlimited Bookmarks
Free users are limited to 4
—
📜 Unlimited History
Free users are limited to 4
—
📥 Unlimited Downloads
Free users are limited to 1
—
Risk-Free Timeline
Today: Get Instant Access
Listen to full summaries of 26,000+ books. That's 12,000+ hours of audio!
Day 2: Trial Reminder
We'll send you a notification that your trial is ending soon.
Day 3: Your subscription begins
You'll be charged on Nov 24,
cancel anytime before.
Consume 2.8× More Books
2.8× more books Listening Reading
Our users love us
1M+ readers
Trustpilot Rating
TrustPilot
4.6 Excellent
This site is a total game-changer. I've been flying through book summaries like never before. Highly, highly recommend.
— Dave G
Worth my money and time, and really well made. I've never seen this quality of summaries on other websites. Very helpful!
— Em
Highly recommended!! Fantastic service. Perfect for those that want a little more than a teaser but not all the intricate details of a full audio book.
— Greg M
Save 62%
Yearly
$119.88 $44.99/year/yr
$3.75/mo
Monthly
$9.99/mo
Start a 3-Day Free Trial
3 days free, then $44.99/year. Cancel anytime.
Unlock a world of fiction & nonfiction books
26,000+ books for the price of 2 books
Read any book in 10 minutes
Discover new books like Tinder
Request any book if it's not summarized
Read more books than anyone you know
#1 app for book lovers
Lifelike & immersive summaries
30-day money-back guarantee
Download summaries in EPUBs or PDFs
Cancel anytime in a few clicks

Why one summary?

Scanner
Find a barcode to scan

⭐
⭐
⭐
We have a special gift for you
Open
38% off
DISCOUNT FOR YOU
⭐
⭐
⭐
$79.99
$49.99/year
Only $4.16 per month
Continue
2 taps to start, super easy to cancel
Settings
General
Widget
Loading...