api: YAML JSON TOON Database version: 1.0.0 format: json dataset: id: 37 slug: behavioral-design-patterns title: Behavioral Design Patterns description: "Patterns for communication between objects: Observer, Strategy, Command, Iterator, State, Template Method, Visitor, Mediator, Chain of Responsibility, Interpreter." summary: "Behavioral design patterns that assign responsibilities and manage communication: Observer, Strategy, Command, Iterator, State, Template Method, Visitor, Mediator, Chain of Responsibility and Interpreter, each with intent, structure, uses, pros, cons and related patterns." use_when[2]: You need a pattern for how objects collaborate or distribute behavior.,"You are weighing Strategy against State, or Observer against Mediator." caveats[2]: Several behavioral patterns look alike structurally and differ in intent (Strategy and State).,Language features such as first-class functions can replace some of them. related[4]: creational-patterns,structural-patterns,solid-principles,design-pattern-anti-patterns category: Design Patterns category_slug: design-patterns tags: "design-patterns,behavioral,observer,strategy,command,state" view_count: 0 created_at: 1777673262 updated_at: 1777673262 entry_count: 10 fields[10]{section,field,type,example}: patterns,name,string,Observer patterns,intent,string,Define a one-to-many dependency between objects… patterns,also_known_as,string,"Publish-Subscribe, Event-Subscriber" patterns,structure_brief,string,Subject maintains list of Observer objects; not… patterns,use_cases,array,"[5 items]" patterns,pros,string,Loose coupling (subject doesn't know observer d… patterns,cons,string,"Memory leaks if observers not unregistered, une…" patterns,implementation_notes,string,"Push vs pull models: push sends data with notif…" patterns,related_patterns,array,"[4 items]" patterns,also_known_as_as,string,"Action, Transaction" data: patterns[10]: - name: Observer intent: "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified automatically." also_known_as: "Publish-Subscribe, Event-Subscriber" structure_brief: Subject maintains list of Observer objects; notifies them on state change via update() method. use_cases[5]: "Event handling systems (UI events, custom events)",Model-View-Controller (View observes Model),Real-time dashboards and monitoring,Message queues and event buses,"Reactive programming (RxJS, ReactiveX)" pros: "Loose coupling (subject doesn't know observer details), dynamic subscription/unsubscription, supports broadcast communication." cons: "Memory leaks if observers not unregistered, unexpected updates can cause performance issues, hard to debug due to indirect flow." implementation_notes: "Push vs pull models: push sends data with notification; pull observers query subject. Thread safety required in concurrent systems. Java's java.util.Observer deprecated in favor of PropertyChangeListener and modern event buses." related_patterns[4]: Mediator,Publish-Subscribe,Reactive Streams,Event Emitter - name: Strategy intent: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it." also_known_as: Policy Pattern structure_brief: Context class delegates to a Strategy interface; concrete strategies implement different algorithms. use_cases[5]: "Sorting algorithms (quick sort, merge sort, bubble sort)","Compression algorithms (zip, gzip, bzip2)","Payment methods (credit card, PayPal, crypto)","Validation strategies (email, phone, credit card)","Navigation algorithms (driving, walking, cycling)" pros: "Eliminates conditional statements, algorithms are isolated (open/closed), easy to add new strategies, enables runtime strategy switching." cons: "Client must know strategies to choose appropriately, increased number of objects, may be overkill for only 1-2 strategies." implementation_notes: Strategies often passed via constructor (dependency injection) or setter. Can be combined with Factory to auto-select strategy. Functional programming often replaces with first-class functions/lambdas. related_patterns[4]: Factory Method,Command,Template Method,Bridge - name: Command intent: "Encapsulate a request as an object, thereby allowing parameterization of clients with different requests, queuing of requests, and support for undoable operations." also_known_as_as: "Action, Transaction" structure_brief: Command interface declares execute(); ConcreteCommand binds Receiver and invokes its action; Invoker holds and calls command; Client creates concrete command. use_cases[5]: "Undo/Redo systems (text editors, graphics apps)",Macro recording and playback,Transaction queues and job scheduling,Remote procedure calls (RPC),GUI menu items and toolbar buttons pros: "Decouples sender and receiver, easy to add new commands, supports undo/redo via Memento, enables command queuing and logging." cons: "Can lead to many small command classes, complexity increases with composite commands, may not be necessary for simple direct calls." implementation_notes: Command often includes undo() method. Macro commands combine multiple commands. Command pattern is foundation of CQRS (Command Query Responsibility Segregation). Used heavily in Android onClick listeners and iOS target-action. related_patterns[4]: Memento,Composite,Chain of Responsibility,Mediator - name: Iterator intent: Provide a way to access elements of an aggregate object sequentially without exposing its underlying representation. also_known_as: Cursor structure_brief: "Iterator interface defines next(), hasNext(); ConcreteIterator tracks position; Aggregate creates iterator; Collection implements iteration logic separately." use_cases[5]: "Traversing collections (lists, trees, graphs)","Different iteration orders (in-order, pre-order, post-order)",Filtering or transforming during iteration,Parallel iteration of multiple collections,Lazy loading / infinite sequences pros: "Single Responsibility (collection vs iteration), multiple simultaneous iterators, simplifies client code, supports different traversal strategies." cons: "Increased complexity for simple collections, overhead for small data sets, mutable collections may require careful iterator invalidation." implementation_notes: "Modern languages often have built-in iterators/generators (Python yield, JavaScript generator functions, C# IEnumerable). Fail-fast iterators throw ConcurrentModificationException if collection modified during iteration. External iterator (client controls iteration) vs internal iterator (collection controls)." related_patterns[3]: Composite,Generator (lazy iteration),Visitor - name: State intent: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. also_known_as: State Machine structure_brief: Context delegates to State interface; ConcreteState implements behavior for that state; State transitions change Context's state object. use_cases[5]: Workflow systems (document approval states),"Game character AI (idle, patrol, attack, flee)","UI components (button states: enabled/disabled/loading)","Network connections (connecting, connected, disconnected)","Vending machines (no money, has money, sold out)" pros: "Eliminates large conditional statements on state, state-specific logic is localized, easier to add new states, adheres to Open/Closed Principle." cons: "Can be over-engineered for simple state changes, many small state classes increase class count, state transition logic can be scattered." implementation_notes: State transitions may be triggered by context or by state objects. Can be implemented with polymorphism or with state pattern tables. Finite State Machine (FSM) libraries often implement this. States can be implemented as singletons if stateless. related_patterns[2]: Strategy,"State Pattern vs Strategy: Strategy chooses algorithm; State changes behavior based on internal conditions." - name: Template Method intent: "Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps without changing the algorithm's structure." also_known_as_as: Template Pattern structure_brief: AbstractClass defines templateMethod() with invariant steps and abstract/primitives for variant steps; ConcreteClass implements variant steps. use_cases[5]: Frameworks and libraries (skeleton code with hooks),Data processing pipelines (read -> transform -> validate -> write),Game AI behavior trees,Test fixtures (setup -> test -> teardown),Document generation (template with placeholders) pros: "Code reuse (common algorithm in base), inversion of control (Hollywood Principle: \"Don't call us, we'll call you\"), enforces algorithm structure." cons: "Base class can become bloated, limited flexibility (subclasses can only override specific steps), may require many small subclasses." implementation_notes: "Template method often final to prevent overriding of skeleton. Hook methods do nothing by default; override selectively. Should call parent implementation or completely replace. Used extensively in Java's AbstractList, AbstractMap." related_patterns[2]: Factory Method (often calls template method),Strategy (Strategy varies entire algorithm; Template Method varies parts) - name: Visitor intent: Represent an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. also_known_as: "" structure_brief: Visitor interface declares visit methods per element type; ConcreteVisitor implements operations; Element interface declares accept(Visitor); ConcreteElement calls visitor.visit(this). use_cases[5]: Compilers (AST traversal),"Object serialization (JSON, XML, binary)",Pretty-printing and formatting,Type checking and validation,Reporting and analytics (visiting data objects) pros: "Adding new operations is easy (new visitor), related operations are grouped together, can accumulate state during traversal, Visitor can work across unrelated classes." cons: "Breaks encapsulation (visitor accesses internals), fragile to element class changes (must update all visitors), element hierarchy must be stable, difficult to add new element types." implementation_notes: "Visitor requires accept() method on all elements. Double dispatch: visitor's method chosen by both visitor type AND element type. Used in Java's FileVisitor (NIO.2) and Expression trees. Considered complex and often overused." related_patterns[3]: Composite (Visitor on composite structure),Iterator (to traverse structure),Interpreter (AST traversal) - name: Mediator intent: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly and lets you vary their interaction independently. also_known_as: "Intermediary, Controller" structure_brief: Mediator interface defines communication methods; ConcreteMediator coordinates Colleagues; Colleagues communicate only through Mediator. use_cases[5]: GUI form coordination (multiple components interacting),Chat rooms / message brokers,Air traffic control system,Middleware and event buses,Complex dialog windows with many controls pros: "Centralizes complex communication, reduces coupling between colleagues, easier to understand interaction flow, each colleague only knows Mediator." cons: "Mediator can become god object (too many responsibilities), introduces single point of failure, colleague changes may still require Mediator changes." implementation_notes: "Mediator often implemented as event bus or message broker. In web dev, Redux/Vuex/Pinia act as state mediators. Colleagues register callbacks with Mediator. Can be combined with Observer pattern where Mediator observes Colleagues." related_patterns[3]: Observer (Mediator often uses Observer),Facade (Facade simplifies interface; Mediator controls interaction),Command - name: Chain of Responsibility intent: Avoid coupling sender of a request to receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass request along chain until handled. also_known_as_as: Responsibility Chain structure_brief: Handler interface defines handle(request) and sets next handler; ConcreteHandler processes or forwards; Clients set up chain and send to first. use_cases[5]: Event bubbling in DOM (browser),Logging systems (debug -> info -> warn -> error),"Middleware pipelines (Express, Koa, ASP.NET)",Authentication/authorization chains,Help systems (button -> panel -> window help) pros: "Decouples sender and receiver, flexibility in assigning responsibilities at runtime, can add/remove handlers dynamically, simplifies objects (each handles one concern)." cons: "Request may go unhandled, hard to debug flow (which handler?), order matters critically, may have performance overhead for long chains." implementation_notes: "Chain built explicitly or via configuration. Can be static or dynamic. Each handler decides whether to handle and stop propagation, or pass to next. In web frameworks, middleware order is critical. Stop propagation via returning response or throwing exception." related_patterns[3]: Command (commands can be chained),Decorator (wraps object; CoR passes request),Observer - name: Interpreter intent: "Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language." also_known_as: "" structure_brief: AbstractExpression declares interpret() method; TerminalExpression implements leaf nodes; NonTerminalExpression combines sub-expressions; Context holds global state (optional). use_cases[5]: Regular expressions,SQL query parsing,Mathematical expression evaluators,Configuration file parsers,Domain-specific languages (DSL) pros: "Easy to extend grammar (new expressions), straightforward implementation for simple languages, changing/growing grammar is easy." cons: "Complex grammars require many classes, inefficient for complex languages (better to use parser generators), maintains interpreter class per rule (maintenance)." implementation_notes: "Best for simple grammars; complex languages use parser generators (ANTLR, Yacc). Interpret() often recursive. Abstract Syntax Tree (AST) built first, then interpreted. Can add operations via Visitor without modifying expressions. Used in JavaScript's eval, Python's ast module." related_patterns[3]: Composite (expression trees are composites),Visitor (to evaluate/operate on AST),Builder (to construct complex expressions)