Your shop has a discount rule that changed three times this quarter, a cart icon that must update in four places, and a support request: “can the customer undo that?” Each is a question about how objects talk to each other and who decides what happens next.

Key takeaways

  • The 1994 Gang of Four book lists 23 patterns, and 11 of them are behavioral: they deal mainly with communication between objects.

  • Strategy swaps one algorithm for another at run time, so a new rule means a new class and no edit to the code that uses it.

  • Observer lets one object notify any number of listeners, but every listener that subscribes must also unsubscribe, or it leaks.

  • Command turns an action into an object, which is what makes undo, redo, queues and logs possible.

  • In languages with first-class functions, a plain function often does the job of a Strategy or Command without any class.

Working definition
A behavioral design pattern is a reusable way of arranging how objects communicate and share responsibility, so that behaviour can change without rewriting the objects that depend on it.

The problem: who decides what happens next

In part 3 of this series we looked at how objects are wrapped and connected. Behavioral patterns come next because a connected system still has to decide who does the work and who hears about it. Wikipedia’s summary of the Gang of Four catalogue, Design Patterns (Gamma, Helm, Johnson and Vlissides, 1994), says most behavioral patterns are specifically concerned with communication between objects. It lists eleven: Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template method and Visitor.

Eleven is too many for one article, and in everyday code three do most of the work. Strategy, Observer and Command each answer a question you meet in almost every application: how do I change a rule, how do I react to a change, and how do I treat an action as data?

One small shop carries every example below. It has a cart, items with a price, and three requests that keep arriving from the business:

interface Item { id: string; name: string; price: number; } 

Strategy: swap the rule, keep the caller

The strategy pattern, also called the policy pattern, enables selecting an algorithm at run time. Instead of implementing one algorithm directly, the code receives instructions about which one in a family of algorithms to use. Wikipedia adds that this lets the algorithm vary independently of the clients that use it.

The naive version of our price rule is an if chain inside the cart: if the customer has a coupon, do this; if the order is over a threshold, do that. Every new promotion reopens and risks the cart class. With a strategy, each rule lives in its own class behind one interface:

interface PricingStrategy { price(subtotal: number): number; } class NoDiscount implements PricingStrategy { price(subtotal: number) { return subtotal; } } class PercentOff implements PricingStrategy { constructor(private percent: number) {} price(subtotal: number) { return subtotal * (1 - this.percent / 100); } } class Cart { private items: Item[] = []; constructor(private pricing: PricingStrategy) {} setPricing(p: PricingStrategy) { this.pricing = p; } total() { const subtotal = this.items.reduce((sum, i) => sum + i.price, 0); return this.pricing.price(subtotal); } } const cart = new Cart(new NoDiscount()); cart.setPricing(new PercentOff(10)); // chosen at run time 

A worked example: three items at 20, 15 and 15 make a subtotal of 50. NoDiscount returns 50. PercentOff(10) returns 45. A later FreeShippingOver(50) rule is one new class and one line where the strategy is chosen. The cart never changes.

Tip
Wikipedia notes that a strategy can be stored as a function pointer, a first-class function or a class instance. In TypeScript or JavaScript, type Pricing = (subtotal: number) => number is often enough, and the interface above is just a more explicit way to say the same thing.

If your code grows a new branch every time the business invents a rule, the rule wants to be an object.

Observer: one change, many listeners

In the observer pattern an object called the subject keeps a list of its dependents, the observers, and notifies them automatically when its state changes, usually by calling one of their methods. It creates a one-to-many dependency without tight coupling: the subject only knows a standard interface, not the concrete types listening. It is how GUI toolkits and MVC frameworks usually react to input.

In the shop, the cart icon, an analytics call and a low-stock warning all care when the cart changes. Without the pattern, add() would call all three directly and know about each. With it, the cart just announces the change:

type Listener = (items: Item[]) => void; class Cart { private items: Item[] = []; private listeners = new Set(); subscribe(fn: Listener): () => void { this.listeners.add(fn); return () => { this.listeners.delete(fn); }; // unsubscribe } add(item: Item) { this.items.push(item); this.listeners.forEach(fn => fn(this.items)); } } const stop = cart.subscribe(items => { badge.textContent = String(items.length); }); // when the header component is removed: stop(); 

Returning an unsubscribe function from subscribe is a cheap way to keep registration and removal together. It matters because of a known drawback. Wikipedia calls it the lapsed listener problem: if the subject holds strong references to its observers, they cannot be garbage collected even when nothing else needs them, and forgetting to unregister leaves them behind.

Caution
Observer is synchronous and direct: the subject calls the observers itself, with no broker in between. That is the difference from publish–subscribe, which Wikipedia describes as using an intermediary. If a listener is slow or throws an error, it can slow or break the code that triggered the change.

“Observer and publish–subscribe are the same thing.”

They are close relatives. In Observer the subject and observers hold direct references to each other and the call is usually synchronous. Publish–subscribe puts a broker or topic channel between senders and receivers, which allows asynchronous, many-to-many delivery across systems.

Command: make an action an object

The command pattern encapsulates everything needed to perform an action later: the method to call, the object that owns it and the arguments. Wikipedia names four terms that go with it. A command knows a receiver and calls it. An invoker runs commands without knowing what they do. The client wires them together.

The reason to bother is that an action you can hold in a variable can also be stored, queued, logged and reversed. Wikipedia lists multi-level undo, macro recording, thread-pool work queues and rollback as typical uses. Our cart can support undo like this:

interface Command { execute(): void; undo(): void; } class AddItem implements Command { constructor(private cart: Cart, private item: Item) {} execute() { this.cart.add(this.item); } undo() { this.cart.remove(this.item.id); } } class History { private done: Command[] = []; private undone: Command[] = []; run(c: Command) { c.execute(); this.done.push(c); this.undone = []; } undo() { const c = this.done.pop(); if (c) { c.undo(); this.undone.push(c); } } redo() { const c = this.undone.pop(); if (c) { c.execute(); this.done.push(c); } } } 

The buttons and keyboard shortcuts now call history.run(new AddItem(cart, book)) and history.undo(). Neither one knows how an item is added or removed. Note the one detail people forget: after a new command runs, the redo list is cleared, because redoing an old action on top of a new one would make no sense.

This is not new. Wikipedia’s history section says the first published mention of using a command class for interactive systems appears to be a 1985 article by Henry Lieberman, and that the first published description of multi-level undo and redo with a command class and a history list appears to be in the first (1988) edition of Bertrand Meyer’s Object-Oriented Software Construction. Wikipedia words both as “appears to be”, and so do we.

If you store or send commands as data, for example in a job queue, writing them as JSON is natural. You can check the shape of those messages in our JSON formatter and validator.

“Every callback is an Observer and every function is a Strategy, so patterns are just jargon.”

Wikipedia itself says the central ideas of Command closely mirror first-class and higher-order functions. In a language with those, you may well write less code. The pattern still gives you a name for the idea, a shared vocabulary for your team and a checklist of what to handle, such as unsubscribing or clearing the redo list.

Choosing between them

  • The same job can be done by several interchangeable rules, and you pick one at run time: Strategy.

  • One thing changes and several unrelated parts must react, without the source knowing them: Observer.

  • You need to queue, log, schedule, undo or replay an action: Command.

  • Behaviour depends on which state an object is in: State, a close cousin of Strategy where the object changes its own strategy.

  • Many objects talk to many others and the links are tangled: Mediator.

As with the earlier parts, the honest test is whether you can name the change the pattern makes cheap. If the discount rule will never change, an if is fine. If only one component listens, call it directly. A pattern that has no second variant, listener or undo behind it is just extra code. If you want to check an input rule that one of your strategies uses, such as a coupon code format, our regex tester lets you try the expression before it goes into a class.

A checklist you can run today

  • Search for long if or switch chains that choose a price, a validation rule or a format. Each is a Strategy candidate.

  • List every place that calls three or more other components after a single change. Replace those calls with a subscription.

  • For each subscription, find the line that unsubscribes. If it does not exist, you have a lapsed listener waiting to happen.

  • Pick one user action that people ask to undo. Write it as a command with execute and undo, and test that undo restores the exact earlier state.

  • Check that your history clears the redo list after a new command runs.

  • Write down the name of the change each pattern makes cheap. If you cannot name one, leave the code as it is.

If a system has grown many of these hidden decision points and nobody has a map of who calls whom, the AIGS systems analysis service starts with exactly that kind of map.

Further reading
The behavioral pattern list and the book’s publication details are on Wikipedia’s Design Patterns article. For each pattern in this guide, see Strategy pattern, Observer pattern and Command pattern. The overall list of behavioral patterns, including ones outside the book, is on Behavioral pattern. Wikipedia pages change, so treat them as a starting point and read the book for the original definitions.

Part 4 of 14 — Engineering Foundations series

Previous: Structural Design Patterns: Adapter, Decorator and Facade Explained. Next: UML class diagrams engineers actually use, which turn patterns like these into pictures a team can review.

Browse the rest of the series on the AIGS blog, or see how we apply it in client work on the services page.

Originally published at ai-gs.net.