Behavioral patterns identify common communication patterns between objects. Strategy defines a family of interchangeable algorithms selected at runtime. State allows an object to alter its behavior when its internal state changes. Observer defines a 1-to-N subscription dependency. Command encapsulates a request as an object, enabling undo/redo history.
A GPS navigation app: you choose your travel Strategy (Fastest Highway vs Scenic Walk vs Bicycle Path), while the navigation voice acts as an Observer broadcasting turn updates to your smartwatch and car display.
Hold the picture while you read the contract above and the moves below; the analogy is what makes the abstraction checkable when the class diagram gets large.
Strategy: Define algorithm interface (e.g. IRouteStrategy), inject concrete strategy into Navigator context
Observer: Subject maintains subscriber list; notifies all observers via onUpdate() event callbacks
State: Context delegates behavior to current State object; transitions state upon events without massive switch cases
Command: Encapsulate actions with execute() and undo() methods for transaction journals
// Strategy Pattern: Dynamic Sorting Algorithm Strategy
export interface ISortStrategy<T> {
sort(items: T[]): T[];
}
export class QuickSort<T> implements ISortStrategy<T> {
sort(items: T[]): T[] { return [...items].sort(); }
}
export class ReverseSort<T> implements ISortStrategy<T> {
sort(items: T[]): T[] { return [...items].sort().reverse(); }
}
export class SorterContext<T> {
constructor(private strategy: ISortStrategy<T>) {}
setStrategy(strategy: ISortStrategy<T>) { this.strategy = strategy; }
executeSort(data: T[]): T[] { return this.strategy.sort(data); }
}Strategy and State eliminate cyclomatic complexity ($O(1)$ polymorphic dispatch vs $O(N)$ nested conditional branches).