Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Behavioral Patterns

Part of the unified study index: Home · canonical comparisons in selection guide.

How objects talk, share work, and evolve over time. All behavioral pages follow the same template: intent, a concrete scenario, structure diagram, trade-offs, usage guidance, runnable examples, an exercise, and a self-check.

Members

  • Strategy — swap one step of an algorithm at runtime by delegating to a chosen variant.
  • Chain of Responsibility — pass a request along handlers until one claims it.
  • Command — package requests as objects so they can be queued, logged, and undone.
  • Interpreter — evaluate tiny languages with composable expression objects.
  • Iterator — traverse a collection without exposing its storage.
  • Mediator — route peer messages through one hub instead of a mesh.
  • Memento — snapshot private state for later restore without exposing it.
  • Observer — broadcast one subject’s changes to many subscribers.
  • State — change behavior with internal status by delegating to the active state.
  • Template Method — fix an algorithm’s skeleton, let subclasses vary steps.
  • Visitor — add operations over stable element types without editing them.

Confusable trio

QuestionStrategyStateTemplate Method
Who picks the active variant?The caller, at wiring timeThe object itself, as status evolvesNobody at runtime — the subclass fixed at build time
How does it change?Swap the delegated objectTransition between state objectsOverride the primitive step
Varies what?One whole step implementationBehavior per status plus transitionsOne step inside a fixed skeleton
Use the shop exampleCheckout picks card vs cashPlayer moves stopped → playing → pausedCSV vs PDF share fetch/save, differ in format

Rule of thumb: caller picks → Strategy; status evolves → State; skeleton fixed with one open step → Template Method.