Varying behavior: strategy, command and observer
Compare behavioral patterns that vary algorithms, encapsulate requests, and decouple event propagation while analyzing their operational consequences.
Contentsand lesson path
On this page
- The Problem of Behavioral Volatility
- Strategy: Interchangeable Algorithmic Variants
- Command: Reifying Execution into First-Class Objects
- Observer: Decoupled Event Notification
Lessons of Design Patterns
- Patterns as named trade-offs: forces, solution, consequences Concept · 15 min
- Varying behavior: strategy, command and observer Concept · 25 min
- Shaping boundaries: adapter, facade and decorator Concept · 20 min
- Organizing domain logic and persistence: from transaction script to data mapper Concept · 25 min
- Replacing a conditional maze with strategy and adapter Lab · 30 min
- Pattern selection and overuse check Knowledge check · 8 questions
What you will learn
- Select a creational, structural or behavioral pattern for a stated design force and explain its consequences.
Prerequisites: Software Design Principles
01. The Problem of Behavioral Volatility
In modern application engineering, business rules change far more rapidly than data schemas or infrastructure plumbing. A billing engine that calculates customer discounts according to a single tier model today may be asked to support seasonal promotions, volume-based tiers, and jurisdiction-specific sales tax exemptions tomorrow.
When codebases attempt to handle shifting behavioral requirements using nested conditional ladders (if/else or switch statements), complexity grows exponentially. Each new variation adds branches, widens unit test matrices, and raises the likelihood of regression errors in unrelated execution paths.
Behavioral patterns solve this challenge by decoupling the trigger of an action from its execution mechanics. Three of the most pervasive behavioral patterns are Strategy, Command, and Observer. While all three introduce runtime flexibility, they address fundamentally different architectural forces and impose distinct operational consequences.
02. Strategy: Interchangeable Algorithmic Variants
The Strategy pattern defines a family of algorithms, encapsulates each one inside a separate class, and makes them interchangeable behind a uniform interface. The client object (often termed the context) maintains a reference to a strategy instance and delegates algorithm execution to it.
Forces That Demand Strategy
- Multiple variants of a specific calculation or operational algorithm must coexist within the same application.
- The selection of the active algorithm depends on runtime context, such as customer subscription tier, geographical region, or dynamic feature flags.
- The client should remain entirely agnostic of algorithmic implementation details, external mathematical libraries, or internal lookup tables.
Structural Consequences and Trade-offs Strategy eliminates branch complexity within the client, adhering cleanly to the Open/Closed Principle. Adding a new promotional discount requires authoring a single new strategy class without touching existing production pipelines.
However, Strategy extracts a design cost:
- Class Multiplication: The overall class count increases proportionally with every algorithmic variant.
- Context Leakage: The strategy interface must provide access to whatever contextual data the algorithms need. If different strategies require radically different inputs, the interface risks becoming an unwieldy grab-bag parameter object.
- Client Configuration Burden: Callers or dependency injection factories must understand how to construct and select the appropriate strategy before delegating work.
03. Command: Reifying Execution into First-Class Objects
The Command pattern encapsulates an operational request as an independent object, binding together a target receiver, the specific method to invoke, and all required execution arguments into a single payload.
Forces That Demand Command
- Operations must be scheduled, placed in background execution queues, or retried across worker threads.
- The application requires multi-level undo and redo capabilities, needing commands that maintain reciprocal reverse operations.
- Operations need transactional logging or audit trail persistence before execution takes place.
Structural Consequences and Trade-offs
By transforming an imperative function call into a standalone object with an execute() method, Command decouples the component that issues a request from the component that executes it. A user interface button does not need to know how an invoice is generated; it merely holds a GenerateInvoiceCommand and dispatches it upon click.
The primary consequence is object lifecycle overhead:
- Every action requires instantiating a dedicated command instance, which can strain garbage collection under extreme high-frequency event loops.
- Maintaining consistent state for undoable commands requires deep-cloning or snapshotting domain entities, introducing substantial memory pressure if historical command stacks grow unbounded.
04. Observer: Decoupled Event Notification
The Observer pattern defines a one-to-many dependency between objects. When the primary subject changes its internal state, it notifies all registered observer instances automatically, typically invoking a standardized callback method.
Forces That Demand Observer
- Multiple disparate subsystems (such as audit loggers, analytics trackers, email dispatchers, and cache invalidators) must react to a single state transition in a domain entity.
- The subject should have zero compile-time awareness of who is listening or how many observers are currently registered.
- Observers need to attach or detach dynamically at runtime.
The Hidden Trap: Implicit Control Flow While Observer provides magnificent compile-time decoupling, it creates operational complexity at runtime:
- Implicit Execution Order: The subject makes no guarantees regarding the order in which observers are notified. Relying on side effects between observers creates subtle, nondeterministic race conditions.
- Cascading Failure: If observer number three of ten raises an unhandled exception, subsequent observers may never receive the event unless the subject explicitly wraps notifications in defensive error boundaries.
- The Lapsed Listener Memory Leak: If an observer subscribes to a long-lived subject but fails to deregister when destroyed, the subject retains a reference to it, preventing garbage collection and leaking memory over time.
- Reentrancy and Deadlocks: In multithreaded environments, if an observer attempts to modify the subject during a notification callback while holding a lock, the system risks recursive deadlocks or concurrent modification exceptions.
Testing and Verifying Behavioral Variations When establishing automated test suites for behavioral patterns, architects must tailor their testing strategies to the specific decoupling mechanism:
- Testing Strategy Invariants: Because strategies share a uniform polymorphic interface, developers can author a standardized parameter-driven test suite. This suite passes identical test vectors across every strategy implementation to verify baseline contracts, while dedicated unit tests verify edge conditions unique to specific algorithms.
- Testing Command Pipelines: Commands are tested in two distinct phases: first, verifying that the command object correctly captures intent and mutates the receiver upon calling
execute(); second, verifying that command invokers or queues correctly sequence and schedule command instances without dropping payloads. - Testing Observer Topologies: Because observers communicate via implicit dispatch, unit testing subjects requires verifying that notifications are emitted with correct event payloads. However, end-to-end testing must explicitly assert that slow observers do not exhaust connection pools and that failed subscribers do not block sibling subscribers from receiving notifications.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.