Behavioral Patterns Deep Dive
Master Strategy, Command, State, Iterator, and Template Method patterns for object interaction.
What you'll learn
- Strategy: interchangeable algorithms
- Command: encapsulate actions as objects
- State: behavior changes with internal state
- Template Method: algorithm skeleton in base class
Concept
Behavioral Patterns Deep Dive
Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. They describe patterns of communication between objects.
Strategy
Defines a family of interchangeable algorithms, each encapsulated behind a common interface. The client can swap algorithms at runtime. Example: a PaymentProcessor with strategies for CreditCard, PayPal, and Crypto. Without Strategy, you would have a giant switch statement.
Command
Encapsulates a request as an object, decoupling the sender from the receiver. This enables: queuing requests, logging them, undo/redo (store a stack of commands), and macro recording. Example: a Button object does not know what action it triggers - it holds a Command object and calls command.execute() when clicked.
State
Allows an object behavior to change when its internal state changes. The object delegates to a State object, and changing state means swapping the State delegate. Example: a Document can be in DraftState (allows edit), ReviewState (allows comment), or PublishedState (read-only).
Iterator
Provides sequential access to a collection elements without exposing its underlying representation. JavaScript for...of and Symbol.iterator are built-in iterator support.
Template Method
Defines the skeleton of an algorithm in a base class, deferring specific steps to subclasses. The base class controls the algorithm structure; subclasses fill in the details.
Example
// Strategy: interchangeable algorithms
class Sorter { constructor(s) { this.s = s; } setStrategy(s) { this.s = s; } sort(a) { return this.s(a); } }
const bubbleSort = (a) => a.slice().sort((x, y) => x - y);
const quickSort = (a) => { if (a.length <= 1) return a; const p = a[0], r = a.slice(1]; return [...quickSort(r.filter(x => x < p)), p, ...quickSort(r.filter(x => x >= p))]; };
const sorter = new Sorter(bubbleSort);
console.log('Bubble:', sorter.sort([3, 1, 4, 1, 5]));
sorter.setStrategy(quickSort);
console.log('Quick:', sorter.sort([3, 1, 4, 1, 5]));
// Command: undo/redo
class AddTextCmd { constructor(ed, t) { this.ed = ed; this.t = t; } execute() { this.ed.content += this.t; } undo() { this.ed.content = this.ed.content.slice(0, -this.t.length); } }
class Editor { constructor() { this.content = ''; this.h = []; } execute(c) { c.execute(); this.h.push(c); } undo() { const c = this.h.pop(); if (c) c.undo(); } }
const ed = new Editor();
ed.execute(new AddTextCmd(ed, 'Hello '));
ed.execute(new AddTextCmd(ed, 'World'));
console.log(ed.content);
ed.undo();
console.log(ed.content);
The Sorter delegates to a strategy function, swappable at runtime. The Editor uses Command objects with execute/undo to implement undo/redo.
Try it
- Code Diff
Strategy changes produce diffable code - compare algorithm variants.
Common mistakes
The mistake
Using Strategy when the algorithms rarely change.
The fix
If there is only one algorithm and no expectation of more, a plain function is simpler than the Strategy pattern.
The mistake
Storing undo state in the Command instead of a memento.
The fix
For complex objects, the Command should store a memento (snapshot) of the receiver state, not try to reverse the operation manually.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.