CMD Guide
HomeOO & Low-Level Design

Behavioral

Step 6 in the OO & Low-Level Design path · 12 concepts · 0 problems

0 / 12 complete

📘 Learn Behavioral from zero

From zero: creational patterns answer "how are objects instantiated"; structural patterns answer "how are objects composed and connected"; behavioral patterns answer "how do objects communicate and divide responsibility at runtime." Behavioral patterns are all about turning a verb, an algorithm, a request, a notification, a state-change, into an object you can swap, queue, or reroute.

Vivid analogy, the Strategy pattern as a navigation app. You want to go from home to office. The app does not bake one route-finder into its code. Instead it offers buttons: Drive, Walk, Cycle, Transit. Each is a self-contained algorithm behind the same interface, computeRoute(start, end). The app (the context) just holds whichever one you picked and calls that method. It never writes if (mode == DRIVE) ... else if (mode == WALK) .... Adding "Scooter" later means writing one new strategy class; the app code is untouched.

Concrete worked example. A checkout needs a shipping cost.

You have replaced a growing if/else with polymorphism, the open/closed principle in action: open to new behavior, closed to modification.

The single key insight: behavioral patterns convert a behavior, an algorithm, request, transition, or notification, into a first-class object so it can be selected, sequenced, or rerouted independently of the code that uses it. Favor composition over conditionals.

✨ Added by the guide to build intuition — not from the source course.

🎯 Guided practice

  1. Easy, Observer (a YouTube channel). A channel must notify all subscribers when it uploads. Step 1, find the one-to-many trigger: "when X changes, notify an unknown number of dependents", that is Observer. Step 2, define the contract: interface Subscriber { void update(String video); }. Step 3, the subject holds a list: Channel keeps List<Subscriber> subs with subscribe() and unsubscribe(). Step 4, push on change: upload(v) loops for (s : subs) s.update(v), O(number of subscribers). Step 5, decouple: Channel knows nothing about concrete subscriber types, only the interface, so an EmailSub or SMSSub can be added with zero changes to Channel. Watch out: a subscriber that is discarded but never unsubscribes keeps getting notified and cannot be garbage-collected (lapsed listener), so always pair subscribe with unsubscribe, or hold observers via weak references.
  2. Medium, State (a vending machine). Model states: NoCoin, HasCoin, Dispensing. Step 1, spot the smell: behavior (insertCoin, pressButton) depends on the current mode and you would otherwise write nested if (state == ...), that signals State. Step 2, make each state a class implementing interface State { void insertCoin(); void pressButton(); }. Step 3, the context delegates: VendingMachine holds State current and forwards every call, e.g. current.pressButton(). Step 4, states drive transitions: in NoCoin.insertCoin() call machine.setState(new HasCoin()); in HasCoin.pressButton() transition to Dispensing, then back to NoCoin once dispensed. Step 5, contrast with Strategy: here the state objects switch the context to one another based on transitions, whereas a Strategy is chosen once by the client and never reassigns itself, this is the canonical distinction interviewers probe. Result: adding a SoldOut state means one new class plus its transition edges, with no edits to a giant conditional that no longer exists.

✨ Added by the guide — work these before the full problem set.

Lessons in this topic

🧠 Review & recall

Active recall is what moves a topic into long-term memory. Flip each card before revealing, then test yourself — your results are saved on this device.

Flashcard
What core question do behavioral patterns answer, and what is the single key insight tying them together?
tap to reveal →
They answer how objects communicate and divide responsibility at runtime. The key insight: convert a behavior, algorithm, request, transition, or notification into a first-class object so it can be selected, sequenced, or rerouted independently of the code that uses it, favoring composition over conditionals.
💡 Creational = how made, Structural = how composed, Behavioral = how they talk.
Flashcard
What is the trigger signal for the Observer pattern, and what is its notification cost?
tap to reveal →
Trigger: a one-to-many relationship where, when one object's (the subject/observable) state changes, an unknown number of dependents (observers) must be notified automatically. notifyObservers() loops over the registered list calling update() on each, so notification is O(number of subscribers).
💡 YouTube channel uploads -> every subscriber gets update(); one-to-many = Observer.
Flashcard
State vs Strategy: what is the canonical distinction interviewers probe?
tap to reveal →
In State, the state objects switch the context to one another based on transitions (e.g. NoCoin.insertCoin() sets HasCoin), so behavior changes at runtime as internal state changes. A Strategy is chosen once by the client and never reassigns itself. Both delegate from a context to interchangeable classes implementing a common interface.
💡 State reassigns itself; Strategy is picked once. Vending machine vs navigation route.
Flashcard
In the Command pattern, name the five roles and what extra capabilities encapsulating a request as an object unlocks.
tap to reveal →
Roles: Command (interface with execute()), ConcreteCommand (binds action to a Receiver), Invoker (holds and triggers the command, e.g. RemoteControl.pressButton()), Receiver (does the real work, e.g. Light), and Client (wires command to receiver). It enables queuing, logging, delayed execution, and undo/redo.
💡 Remote button = Command object; press = execute(). Undo lives here.
Flashcard
In the Memento pattern, what are the three roles and how is encapsulation preserved?
tap to reveal →
Originator: the object whose state is saved/restored; it creates a memento snapshot and uses one to roll back. Memento: a data-only object holding the saved state. Caretaker: tracks mementos over their lifetime but never modifies or inspects them. State is captured and restored without breaking the originator's encapsulation.
💡 Video-game save: Originator saves, Memento holds, Caretaker keeps but never peeks.
Flashcard
When do you reach for Visitor vs Chain of Responsibility, and what does each let you add without modifying existing code?
tap to reveal →
Visitor: add new operations to a fixed set of element types (elements expose accept(visitor)); you add a new visitor class without altering the elements. Chain of Responsibility: pass a request down a line of handlers, each handling it or forwarding to the next; you add or reorder handlers without disturbing the others.
💡 Visitor = new verbs on same objects (IDE refactor tool). CoR = pass the buck down the line (support tiers).
Q1. A vending machine's insertCoin() and pressButton() behave differently depending on whether it is in NoCoin, HasCoin, or Dispensing mode, and each mode transitions the machine to another. Which pattern fits?
Q2. In the Chain of Responsibility customer-support example (TechnicalSupportHandler -> BillingSupportHandler -> GeneralSupportHandler), what does a concrete handler do when it cannot handle the incoming queryType?
Q3. A checkout needs interchangeable shipping cost algorithms: FlatRate (returns 500), ByWeight (returns weight*10), and Free (returns 0), selected via cart.setStrategy(...). Which pattern and principle does this illustrate?
Q4. Which scenario is the textbook fit for the Command pattern's distinctive strength?
Q5. In an office where HR, Finance, and Technical departments would otherwise communicate directly for every request, a central communication office receives all requests and forwards them to the right department. Which pattern is this, and what is its main goal?