DevDocsDev Docs
Design PatternsBehavioral Patterns

Behavioral Patterns

Patterns concerned with algorithms and the assignment of responsibilities between objects

Behavioral Patterns

Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. They describe patterns of communication between objects and how they operate together to accomplish tasks that no single object could accomplish alone.


Pattern Overview

PatternIntentUse When
Chain of ResponsibilityPass requests along a chain of handlersMultiple handlers can process a request
CommandEncapsulate a request as an objectNeed to parameterize, queue, or log requests
InterpreterDefine a grammar and interpret sentencesNeed to evaluate language expressions
IteratorAccess elements sequentially without exposing structureNeed uniform traversal of collections
MediatorDefine simplified communication between classesMany objects communicate in complex ways
MementoCapture and restore object stateNeed undo/redo or state snapshots
ObserverNotify dependents of state changesOne-to-many dependency between objects
StateAlter behavior when internal state changesObject behavior depends on its state
StrategyDefine a family of interchangeable algorithmsNeed to switch algorithms at runtime
Template MethodDefine skeleton of algorithm, defer steps to subclassesAlgorithm structure is fixed, steps vary
VisitorDefine new operations without changing classesNeed to add operations to stable structures

Categorization

By Purpose


Quick Comparison

Communication Patterns

PatternDirectionCouplingUse Case
ObserverOne-to-manyLooseEvent systems, reactive UIs
MediatorMany-to-many (via hub)CentralizedChat rooms, air traffic control
Chain of Resp.One-to-one (sequential)LooseMiddleware, validation

Algorithm Patterns

PatternFlexibilityInheritanceUse Case
StrategySwitch at runtimeCompositionPayment methods, sorting
Template MethodFixed structureInheritanceFrameworks, hooks
CommandQueued/loggedCompositionUndo/redo, transactions

Pattern Selection Guide


TypeScript Implementation Notes

Behavioral patterns in TypeScript leverage:

  • Function composition for strategies and commands
  • Generators for iterators
  • Closures for state encapsulation
  • Event emitters for observers
  • Type guards for visitors
/**
 * Example: Strategy pattern using function composition
 * @description Demonstrates idiomatic TypeScript approach
 */
type SortStrategy<T> = (items: T[]) => T[];

/** Bubble sort implementation */
const bubbleSort: SortStrategy<number> = (items) => {
  const arr = [...items];
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  return arr;
};

/** Quick sort implementation */
const quickSort: SortStrategy<number> = (items) => {
  if (items.length <= 1) return items;
  const pivot = items[0];
  const left = items.slice(1).filter(x => x < pivot);
  const right = items.slice(1).filter(x => x >= pivot);
  return [...quickSort(left), pivot, ...quickSort(right)];
};

/** Sortable collection with swappable strategy */
const createSorter = <T>(strategy: SortStrategy<T>) => ({
  sort: (items: T[]) => strategy(items),
  setStrategy: (newStrategy: SortStrategy<T>) => createSorter(newStrategy),
});

const sorter = createSorter(bubbleSort);
const result = sorter.sort([3, 1, 4, 1, 5, 9]);
//    ^?

Common Combinations

Behavioral patterns often work together:

CombinationPurpose
Command + MementoUndo/redo with state snapshots
Observer + MediatorComplex event routing
Strategy + StateState-dependent algorithms
Iterator + VisitorProcess collection elements
Chain + CommandMiddleware pipelines

Summary

Key Insight: Behavioral patterns help manage complex control flows and communication between objects. They promote loose coupling and make algorithms interchangeable.

Choose your pattern based on:

  • Observer: When changes in one object affect others
  • Strategy: When you need interchangeable algorithms
  • Command: When you need to queue, log, or undo operations
  • State: When object behavior depends on its state
  • Chain: When multiple handlers might process a request

On this page