Skip to content

Behavioural Patterns Summary

All eleven behavioural patterns on one page, with a decision tree for picking one and the pairs interviewers love to mix up, like Strategy vs State.

Builds on Strategy Pattern: Dynamic Runtime Interchangeability, Observer Pattern: Event-Driven Communication and Lifecycle Management & State Transitions

Stage 3core8 min read

Creational patterns are about making objects. Structural patterns are about putting objects together. Behavioural patterns are about who does what, and who talks to whom.

Almost every behavioural pattern does the same thing. It takes a piece of behaviour that is stuck inside one class (an if chain, a hard-coded call, a loop over internals) and gives it its own object. The patterns differ in which piece of behaviour they pull out.

All eleven, grouped by the problem they solve

First, sort the patterns into four buckets. A pattern can fit more than one bucket. The buckets help you ask a first question: what kind of pain am I looking at?

  • Choose or organise behaviour: Strategy swaps an algorithm, State changes behaviour as an object changes state, and Template Method fixes the order of steps while subclasses fill in some of them.
  • Move messages or requests: Observer broadcasts changes, Mediator coordinates peers through a hub, Chain of Responsibility routes a request through possible handlers, and Command turns a request into an object that can be queued, logged or undone.
  • Traverse or operate on structures: Iterator hides how a collection is traversed, while Visitor adds many operations to a set of element types that rarely changes.
  • Represent state or rules: Memento saves a snapshot you can restore later, while Interpreter stores a small language as a tree that can be evaluated.

That covers all eleven patterns. The table below gives the exact intent and an example for each.

All of them in one table

PatternWhat it pulls outOne-line intentExample in this repo
StrategyAn algorithmPick one of several ways to do a job, and swap it at runtimeRide matching: nearest driver, surge, airport queue
ObserverThe list of who caresWhen one object changes, tell everyone who subscribedYouTube channel notifying email and app subscribers
CommandA requestWrap an action in an object so you can queue, log or undo itRemote control buttons for light and AC
StateBehaviour per stateLet an object act differently as its state changes, without a giant switchFood order: placed, preparing, out for delivery
Template MethodThe fixed skeletonFix the order of steps in a base class, let subclasses fill in some stepsSending email and SMS notifications
IteratorThe walking logicGo through a collection without knowing how it is storedYouTube playlist
Chain of ResponsibilityThe routingPass a request along a line of handlers until one takes itSupport tickets: general, billing, technical, delivery
MementoA snapshot of stateSave an object's state and restore it later, without exposing its fieldsText editor undo
MediatorThe communicationMake objects talk through one hub instead of to each otherAir traffic control tower
VisitorOperations over a structureAdd new operations to a stable set of classes without editing themGST, shipping and invoice over cart items
InterpreterThe rules themselvesRepresent sentences of a small language as a tree and evaluate itCoupon eligibility rules

Which one do I need?

Start from the pain you feel in the code, not from the pattern names.

Loading diagram…

Pairs that get mixed up

Interviews ask about these pairs more than about any single pattern.

PairLooks the same becauseThe real difference
Strategy vs StateBoth have a context that delegates to an interface with many implementationsIn Strategy, the client picks the algorithm and it usually stays the same. In State, the states switch themselves: PreparingState moves the order to OutForDeliveryState. States know about each other. Strategies do not.
Command vs StrategyBoth wrap behaviour in an objectStrategy is how to do one job (pay by UPI or card). Command is what to do, as a request you can queue, log or undo (place this order). Different commands do different things. Different strategies do the same thing differently.
Observer vs MediatorBoth cut direct links between objectsObserver is a one-to-many broadcast: the subject doesn't care who listens or what they do. Mediator is many-to-many coordination: the hub knows every participant and decides who should react and how.
Template Method vs StrategyBoth let you vary part of an algorithmTemplate Method uses inheritance: subclasses fill in steps, and the choice is made when the code is compiled. Strategy uses composition (one object holds another): you pass in an object and can swap it at runtime. If the part that varies is a whole algorithm, prefer Strategy.
Chain of Responsibility vs DecoratorBoth are a linked line of objects with the same interfaceIn a chain, any handler can stop the request, and usually only one handles it. In a Decorator, every layer always passes the call on and adds something to it.
Command vs Memento (for undo)Both give you undoCommand undoes by running the reverse action (withdraw undoes deposit). Memento undoes by restoring a saved copy of the state. Memento is simpler when reverse actions are hard, but it uses more memory.
Visitor vs StrategyBoth pull logic into a separate objectA strategy has one method and works on one kind of input. A visitor has one method per element type and is meant to walk a structure that mixes several types.

Quick rules of thumb

  1. A switch on a type that keeps growing in many places? Try polymorphism first. Use Visitor if the operations keep growing. On Java 21+, use sealed types and pattern matching.
  2. A switch on a status field inside one class? State.
  3. A switch on a mode or option the caller chooses? Strategy.
  4. Copy-pasted methods that differ in two lines? Template Method.
  5. Something needs undo, history or a job queue? Command, plus Memento if reversing is hard.
  6. A class keeps getting edited every time a new listener appears? Observer.
  7. None of the above, and the code is short and rarely changes? Leave it alone. Every pattern on this page adds classes and one more hop to follow in a debugger. A 15-line switch that changes once a year costs less than any of them.

Interview questions

"What do behavioural patterns have in common?"

They all deal with how objects share work and talk to each other. Most of them take a piece of behaviour that is stuck inside one class, like an if chain or a direct call, and move it into its own object so it can change on its own.

"What is the difference between Strategy and State?"

The structure is almost identical. In Strategy the client chooses the algorithm and the strategies don't know each other. In State the object moves between states on its own, and each state decides what the next state is.

"How is Observer different from Mediator?"

Observer is a one-to-many broadcast where the subject doesn't know or care what listeners do. Mediator is a central hub that knows all participants and contains the logic of how they coordinate, so objects stop referring to each other directly.

"Template Method or Strategy, which would you pick?"

Usually Strategy. You can swap it at runtime, test it alone, and it does not lock you into a class hierarchy. Template Method is fine when the step order is fixed and only one or two small steps differ, like in framework base classes.

"Chain of Responsibility and Decorator both chain objects. How are they different?"

In a chain, each handler decides whether to handle the request or pass it on, and the chain can stop early. In a Decorator, every layer always calls the next one and adds behaviour around it, so the call always reaches the core object.

"Which patterns help with undo?"

Command, where each command knows how to reverse itself, and Memento, where you save a snapshot of the object's state and restore it later. They are often used together: the command stores a memento before it runs.

"Which behavioural patterns are least used, and why?"

Interpreter, because existing tools like regex, SQL, SpEL and rules engines cover most needs. Visitor is also less common now, because Java 21 sealed types with pattern matching switch give the same compile-time safety with less code.

Common mistakes

  • Picking a pattern from its class diagram instead of its intent. Strategy and State can both look like “hold an interface”. Ask which change you want to make cheap.
  • Replacing every small if with classes. A pattern pays off when the variation keeps coming back, not just because a branch exists.
  • Hiding business logic behind too many hops. A named object should make it clearer who owns the logic. If the code is harder to trace and not safer to change, simplify it.
  • Calling a central object a Mediator when it does everybody's work. A mediator only coordinates. It should not become the whole application.
  • Choosing Visitor when element types change frequently, or Interpreter before rules actually need a language.

Takeaways

All eleven patterns move or organise behaviour, but each protects against a different kind of change. Start with the pain: algorithm choice, object state, notifications, request routing, undo, traversal, coordination between objects, operations over stable types, or configurable rules. Then pick the smallest pattern that makes the next likely change safer. If plain methods are still clear, keep them.

In this topic

Done with this topic?

How well do you know it?