Design Patterns

Behavioral patterns

How objects communicate and share responsibilities.

  • 11patterns
  • 83animated steps
  • 66code examples

Behavioral patterns organize the exchanges between objects: who notifies whom, who decides, who executes. They avoid long chains of conditionals and direct dependencies between classes.

The patterns

  1. 13Chain of Responsibility

    Pass a request along a chain of handlers: each one handles it, stops it, or forwards it to the next.

  2. 14Command

    Turn a request into a standalone object: it can then be passed as a parameter, queued, logged or undone.

  3. 15Iterator

    Traverse the elements of a collection without exposing its internal representation (list, tree, paginated APIโ€ฆ).

  4. 16Mediator

    Reduce chaotic dependencies between objects by forcing them to communicate through a central mediator object.

  5. 17Memento

    Capture and later restore an object's internal state without violating its encapsulation.

  6. 18Observer

    Define a subscription mechanism to automatically notify several objects of a state change.

  7. 19State

    Let an object change its behavior when its internal state changes, as if it had changed class.

  8. 20Strategy

    Define a family of interchangeable algorithms and let you choose which one to use at runtime.

  9. 21Template Method

    Define the skeleton of an algorithm in a base class, letting subclasses override certain steps without changing its structure.

  10. 22Visitor

    Separate an algorithm from the object structure it operates on, so you can add operations without modifying those classes.

  11. 23Interpreter

    Define the grammar of a small language and an interpreter that evaluates sentences in that language.

At a glance

PatternAlso known asUse it for
Chain of Responsibilityโ€”HTTP middlewares (Laravel, Express, ASP.NET, Go)
CommandActionUndo / redo, action history
IteratorCursorComplex collections (trees, graphs)
Mediatorโ€”Tightly interconnected components (forms, UI)
MementoTokenUndo / redo, save points
ObserverPublish-SubscribeDomain events (OrderPaidโ€ฆ)
StateObjects for StatesState machines: orders, payments, workflows
StrategyPolicySeveral variants of the same algorithm
Template Methodโ€”Algorithms with a fixed structure and variable steps
Visitorโ€”Stable structure, operations added frequently
Interpreterโ€”Simple DSLs: business rules, filters, formulas

Other families

  • Creational patterns 5 patterns

    How to create objects flexibly, without coupling your code to concrete classes.

  • Structural patterns 7 patterns

    How to assemble classes and objects into larger structures that stay flexible.