Eleven patterns in eleven lessons: the catalog's largest family, and also its most confusable — half a dozen of its members share a diagram and are told apart only by intent. This lesson is the module's final map: the complete table, the five head-to-heads that resolve 90% of real-world doubts, a decision flowchart, the combinations that work as a team, and the review of what got installed in every corner of PideYa. When you finish it, the entire GoF catalog — creational, structural, and behavioral — will be in your toolbox.
Contents
- The table of the eleven
- The pairs everyone confuses, face to face
- Decision guide
- Frequent combinations
- Module 4 on the PideYa map
- Exercises and conclusion
- Closing: the catalog is complete
The table of the eleven
| Pattern | Reifies... | Question it answers | In PideYa |
|---|---|---|---|
| Chain of Responsibility | A request's journey | Which of these should handle this? | OrderHandler: fraud → zone → stock → minimum |
| Command | A request | How do I queue, log, or undo an action? | The panel's Command: accept, cancel, macro |
| Interpreter | Sentences of a language | How do I evaluate rules written as text? | RuleExpression: "total > 30 AND day == FRIDAY" |
| Iterator | A traversal | How do I walk this without knowing its guts? | MenuDepthIterator, paginated history |
| Mediator | A coordination protocol | How do many collaborate without knowing each other? | DispatchCenter: kitchen ↔ couriers |
| Memento | A state snapshot | How do I save and restore without exposing? | Cart.Memento, the menu's restore points |
| Observer | A subscription | How do many find out that one changed? | OrderObserver: customer, courier, kitchen, statistics |
| State | A life-cycle stage | What can I do right now? | OrderState: CREATED → ... → DELIVERED |
| Strategy | An algorithm | In which of these ways do I do it? | DeliveryFeeCalculation, AssignmentStrategy |
| Template Method | An algorithm's skeleton | How do I fix the flow and vary steps? | ClosingReport: load → aggregate → format → distribute |
| Visitor | An operation over a structure | How do I add operations without touching the nodes? | MenuVisitor: export, allergens, audit |
The "reifies" column is no ornament: it's the module's summary. All eleven apply the same move — turning an aspect of behavior into an object — and are distinguished by what they turn.
The pairs everyone confuses, face to face
State vs. Strategy
Structural twins (a context delegating to an interface with variants); opposite intent:
| State | Strategy | |
|---|---|---|
| Who changes the delegated object | The states themselves, when transitioning | The outside (config, client), whenever it wants |
| Do the variants know each other? | Yes: each state knows where it goes | No: each strategy ignores its siblings |
| Is there a transition graph? | Yes (draw the stateDiagram) | No: no calculation "transitions" into another |
Litmus test: if the delegated object replaces itself from within, it's State; if it's chosen from outside and the variants form no life cycle, it's Strategy.
Command vs. Strategy
Both encapsulate "code in an object":
| Command | Strategy | |
|---|---|---|
| Encapsulates | That something was requested: the call with its arguments and receiver | How something is done: the algorithm, with no concrete request |
| Typical lifetime | Created per request; queued, stacked, audited, undone | Lives as long as the context; invoked a thousand times |
| Typical interface | execute() with no arguments (everything goes inside) |
calculate(data) with arguments (the data arrives from outside) |
Litmus test: look at the signature. If the method needs no arguments because the object already carries the complete request inside, it's Command; if it receives the data on each call, it's Strategy.
Observer vs. Mediator
Both decouple communication:
| Observer | Mediator | |
|---|---|---|
| Topology | Broadcast: one emits, N anonymous parties listen | Star: N colleagues talk to a center that directs |
| Is there a protocol? | No: each observer reacts on its own, with no guaranteed order | Yes: the mediator decides who does what and when |
| Does the emitter expect a response/coordination? | No: "this happened", and it moves on | Yes: the notice triggers decisions about others |
| Adding an interested party | Subscribe it; nobody else notices | The mediator probably needs to know its role |
Litmus test: does the notifier need someone to decide what happens next (Mediator), or just that whoever cares finds out (Observer)?
Template Method vs. Strategy
The inheritance/composition matchup:
| Template Method | Strategy | |
|---|---|---|
| What varies | Steps of a fixed flow | The entire algorithm |
| Mechanism | Inheritance; decided at instantiation | Composition; swappable at runtime |
| Combining axes of variation | Poorly (one subclass per combination) | Well (one strategy per axis) |
Litmus test: do you need to hot-swap the variant or combine axes? Composition (Strategy). Fixed flow, few stable variants that share context? Template.
Chain of Responsibility vs. Decorator
The cross-family matchup (promised in module 3): both are linked objects with the same interface that delegate to the next.
| Chain of Responsibility | Decorator | |
|---|---|---|
| Delegation | Conditional: each link decides to handle, cut, or pass | Unconditional: each layer always calls the wrapped one |
| The links/layers | Do equivalent things (variants of "handling") | Add distinct responsibilities on top of a core |
| Can it fail to reach the end? | Yes, by design (cut, veto) | No: the call goes through every layer |
| Intent | Find who handles it / filter | Add behavior while preserving the interface |
Litmus test: can some element legitimately cut the chain? Chain. Does everyone always contribute their layer? Decorator.
Decision guide
The question tree to orient yourself (like every guide: a compass, not a law — confirm afterwards against the corresponding head-to-head):
flowchart TD
A[What is your behavior problem?] --> B{Is it about notifying<br/>or coordinating objects?}
A --> C{Is it about encapsulating<br/>a request or operation?}
A --> D{Is it about varying<br/>a behavior?}
A --> E{Is it about operating on<br/>an object structure?}
B --> B1{Broadcast a change to<br/>anonymous interested parties?}
B1 -- Yes --> OBS[Observer]
B1 -- "No: there's a protocol<br/>to direct" --> MED[Mediator]
C --> C1{Queue, undo,<br/>audit the request?}
C1 -- Yes --> CMD[Command]
C1 -- "No: find who<br/>handles it / filter it" --> COR[Chain of Responsibility]
C1 -- "No: it's written as<br/>text in a mini-language" --> INT[Interpreter]
D --> D1{Does it depend on internal state,<br/>with transitions?}
D1 -- Yes --> STA[State]
D1 -- No --> D2{Does the whole algorithm vary,<br/>or steps of a fixed flow?}
D2 -- Whole --> STR[Strategy]
D2 -- Steps --> TM[Template Method]
E --> E1{Just traverse it?}
E1 -- Yes --> ITE[Iterator]
E1 -- "No: add operations<br/>per node type" --> VIS[Visitor]
E --> E2{Save and restore<br/>its state?}
E2 -- Yes --> MEM[Memento]
And the usual reminder, inherited from the scales lesson: the first valid option is none. An if, a direct call, or an enum are still the right answer when the symptom hasn't appeared.
Frequent combinations
Behavioral patterns work as a team better than any other family:
- Command + Memento: the robust-undo duo — inverse when it's symmetric and cheap, picture when the inverse lies. The
ManagementPanelstacks commands; the difficult commands store mementos of their receiver. - Observer + Mediator: the
DispatchCentercan learn about the order's status changes as just another observer (transitionTonotifies) and direct the reaction as a mediator — broadcast to find out, protocol to act. - Composite + Iterator + Visitor: the structures trio — Composite defines the menu's tree, Iterator traverses it without exposing it, Visitor adds operations without touching it. Three lessons, one menu.
- State + Observer: State authorizes the order's transitions; Observer broadcasts the ones that happen. Connected at a single point:
transitionTo. - Mediator + Strategy: the mediator orchestrates; its variable criteria (courier assignment) are injected strategies.
- Template Method + Strategy/Bridge: the fixed flow via inheritance, the hot-swappable axes via composition — Template Method's final exercise over the
Notificationclasses. - Chain + Command: commands can travel along the chain: the reified request looking for its handler.
- Interpreter + Visitor + Flyweight: over the rules AST — evaluate/print/optimize as different visitors, repeated terminals shared.
Note the constant: combinations are not designed "from the catalog" — they emerge because each pattern solves its symptom and the symptoms coexist in the same system.
Module 4 on the PideYa map
The applied review, following an order's journey:
- The order comes in → the validation chain (
FraudHandler→DeliveryZoneHandler→StockHandler→MinimumAmountHandler) approves or rejects it, assembled in configuration and fired by theCheckoutFacade— Chain of Responsibility. - The delivery fee is calculated with the market's
DeliveryFeeCalculation(distance, flat, free with a promotion), and the promotions are evaluated with theRuleExpressions marketing writes as text — Strategy and Interpreter. - The customer edits the cart with return points:
Cart.Mementoin theCartHistory— Memento. - The order lives its life cycle:
OrderStateauthorizes each transition (CREATED → PAID → PREPARING → OUT_FOR_DELIVERY → DELIVERED / CANCELLED) — State — and each legal transition is broadcast toCustomerNotifier,CourierNotifier,KitchenMonitor, andStatsPanel— Observer, settling lesson 01-01's debt. - The restaurant manages from its panel with stackable, undoable, queueable
Commands — Command. - Delivery is coordinated as a star: the
DispatchCentermediates between kitchen, orders, and couriers, with the swappableAssignmentStrategy— Mediator + Strategy. - The menu gets mined: traversed via
Iterable<Dish>(search, streams) and operated on byMenuVisitor(export, allergens, audit) — Iterator and Visitor. - Every night, the closing reports follow
ClosingReport's skeleton with their per-format steps — Template Method.
Exercises
Exercise 1: express diagnosis
For each symptom, name the pattern (and, if you hesitated between two, which one you discarded and why):
- "When the courier marks 'delivered', the customer app, billing, and metrics must react — and next month, the points program."
- "The restaurant onboarding wizard has 6 screens with the same flow (validate → save → next) and different steps per screen."
- "We want support to be able to revert the last 10 actions performed on an order, with an audit of who did what."
- "The commission rate is calculated differently for premium, standard, and new restaurants, chosen by their contract."
- "A price adjustment goes through: automatic validation → zone manager approval → finance approval if it exceeds 10%."
Exercise 2: the head-to-head in code
Without looking at the lessons: write the two "litmus tests" you would use with doubtful code between (a) State and Strategy, (b) Chain and Decorator. Then apply (a) to this case: TaxCalculator receives a TaxRegime in the constructor that never changes after construction and whose variants (GeneralRegime, SimplifiedRegime) don't know each other.
Exercise 3: combining with judgment
The team wants "undo" in the restaurant's menu editor too: every editor operation (rename section, change price, move dish) must be revertible, and so must "rebalance prices" (bulk, with rounding). Design the solution, naming the patterns you would combine and the role each one plays.
Solutions
Solution 1:
- Observer — variable, anonymous interested parties reacting to a change. (Discarded Mediator: nobody directs a protocol; each one reacts to its own concern.)
- Template Method — fixed flow, variable steps per screen. (Discarded Strategy: the whole algorithm doesn't vary and no hot-swapping is needed.)
- Command (+ Memento for the actions without a clean inverse) — reified requests with a history, undo, and auditing.
- Strategy — alternative algorithms chosen from outside (the contract), with no transitions between them. (Discarded State: one regime doesn't "transition" to another through the operations.)
- Chain of Responsibility — the request escalates through handlers that approve it or pass it on, with conditional links (finance only sometimes). (Discarded Decorator: there is cutting and conditions, not layers that always add.)
Solution 2: (a) does the delegated object replace itself from within, following a transition graph? → State; is it chosen by the outside and do the variants ignore each other? → Strategy. (b) can some element legitimately cut the chain? → Chain; does everyone always contribute their layer? → Decorator. The case: Strategy — the outside fixes it at construction, with no transitions and no mutual knowledge. (That it "never changes after construction" doesn't make it something else: the interchangeability is between context instances, not necessarily hot.)
Solution 3: Command as the backbone: each editor operation is a Command with execute()/undo(), stacked in an invoker with a stack (the ManagementPanel pattern). The simple, symmetric operations (renaming) undo by inverse; "rebalance prices" undoes by Memento — its execute() first captures a snapshot of the menu (a deep copy of the Composite, Prototype discipline) and its undo() restores it. Optional and coherent: confirmed changes are broadcast via Observer (the CatalogCacheProxy cache and the search engine want to know). Command provides the uniform framework; Memento steps in only where the inverse falls short — combining means assigning each pattern its symptom, not stacking them for fun.
Conclusion
You can now tell the eleven apart by intent, which is sometimes the only thing that separates them: you know what each one reifies, you have the five head-to-heads with their litmus tests, the decision tree to orient yourself, and the combinations that work because each piece attacks its own symptom. And PideYa stands as a living demonstration: from the chain that filters orders to the visitor that audits the menu, every pattern in the module is installed exactly where its pain called for it.
Closing: the catalog is complete
The 23 GoF patterns are now in your toolbox: the creational ones solved the objects' birth, the structural ones their anatomy, and the behavioral ones their conversations — who notifies whom, where the algorithms live, how what's done gets undone. Even the course's oldest debt, that changeStatus from the first lesson, was settled by Observer with State guarding the door.
But knowing the catalog is not knowing how to use it — it's the difference between owning the tools and being a good carpenter. The questions coming next are the hard ones: how do you choose a pattern for a real problem that doesn't arrive labeled? How do you refactor living code toward a pattern without breaking it? When does a well-applied pattern turn into an anti-pattern? Which patterns do Spring, the JDK, or your company's code actually use? That is the craft, and it's the whole module about to begin: see you in How to Select the Right Pattern.
Software Design Patterns Course
Module 1: Introduction to Design Patterns
- What Are Design Patterns?
- History and Origin of Design Patterns
- Design Principles: SOLID and Other Foundations
- Essential UML for Understanding Patterns
- Classification of Design Patterns
- Advantages and Disadvantages of Using Design Patterns
Module 2: Creational Patterns
- Introduction to Creational Patterns
- Singleton
- Factory Method
- Abstract Factory
- Builder
- Prototype
- Comparing and Choosing Creational Patterns
Module 3: Structural Patterns
- Introduction to Structural Patterns
- Adapter
- Bridge
- Composite
- Decorator
- Facade
- Flyweight
- Proxy
- Comparing and Choosing Structural Patterns
Module 4: Behavioral Patterns
- Introduction to Behavioral Patterns
- Chain of Responsibility
- Command
- Interpreter
- Iterator
- Mediator
- Memento
- Observer
- State
- Strategy
- Template Method
- Visitor
- Comparing and Choosing Behavioral Patterns
Module 5: Applying Design Patterns
- How to Select the Right Pattern
- Practical Examples of Pattern Usage
- Design Patterns in Real Projects
- Refactoring with Design Patterns
- Anti-Patterns: When Patterns Become a Problem
Module 6: Advanced Design Patterns
- Design Patterns in Modern Architectures
- Design Patterns in Microservices
- Design Patterns in Distributed Systems
- Concurrency Patterns
- Design Patterns in Agile Development
