Design Patterns โ Behavioral Patterns
Master Behavioral Design Patterns โ Observer, Strategy, Command, Template Method, and Chain of Responsibility โ that define how objects communicate and distribute responsibilities.
โBehavioral design patterns address how objects communicate and how responsibilities are distributed between them. While Creational patterns answer 'how are objects born?' and Structural patterns answer 'how are objects assembled?', Behavioral patterns answer 'how do objects talk to each other, and who is responsible for what?' There are 10 GoF Behavioral Patterns. We'll focus on the five most commonly encountered in practice. The unifying theme across behavioral patterns is decoupling: separating the sender of a request from the receiver, separating what is done from when it's done, separating an algorithm from the objects it operates on. This decoupling makes systems extensible without modification โ you can add new behaviors, new observers, new commands, new handlers without touching existing code.โ
โThe Observer pattern defines a one-to-many dependency between objects: when the subject changes state, all registered observers are notified and updated automatically. The analogy: a news subscription service. The NewsPublisher is the subject โ it maintains a list of subscribers. Each Subscriber is an observer. When the publisher gets breaking news, it notifies all subscribers. Subscribers can join or leave at any time. No subscriber knows about the others. Software example: a StockMarket subject. When IBM's stock price changes, the subject notifies: a PriceDisplayPanel that updates the UI, a PriceAlertService that sends push notifications if the price crosses a threshold, and an AuditLogger that records the change. The subject just calls notifyObservers() โ it doesn't know or care who is listening. This is the foundation of almost every event-driven system: JavaScript's addEventListener, Java's EventListener, MVC architecture where the Model notifies Views, and all reactive programming frameworks like RxJava and RxJS.โ
โThe Strategy pattern defines a family of algorithms, encapsulates each one in its own class, and makes them interchangeable. The context that uses the algorithm doesn't know which specific algorithm it's running โ it just knows it has a strategy. The classic problem: a data processing system that can sort data by different algorithms โ QuickSort for large datasets, BubbleSort for nearly-sorted data, MergeSort for stable sorting. Without Strategy, you have a switch statement on some algorithm flag. Every time you add a new algorithm, you modify the existing code. With Strategy: define a SortStrategy interface with a sort() method. QuickSortStrategy, BubbleSortStrategy, and MergeSortStrategy each implement it. The DataProcessor context holds a SortStrategy reference. You can switch strategies at runtime โ even let users choose the algorithm. This directly applies to payment systems: PaymentProcessor holds a PaymentStrategy. StripeStrategy, PayPalStrategy, and CryptoStrategy implement it. The payment flow logic stays stable; only the strategy changes. Strategy eliminates type-checking conditionals and makes adding new variants safe and clean.โ
โThe Command pattern encapsulates a request as an object, containing the receiver, the action, and all parameters. The classic use case is undo/redo. In a text editor: InsertCommand stores the position and character to insert. When you execute it, it inserts the character. When you undo it, it removes that character. DeleteCommand stores the deleted character and position. Execute deletes; undo inserts back. FormatCommand stores the formatting change. The editor maintains a command history โ a stack of executed commands. Ctrl+Z pops the top command and calls undo(). The editor (the invoker) doesn't know what InsertCommand does internally. It just calls execute() or undo(). Command enables far more than undo/redo. Command queues let you batch operations and execute them asynchronously or in a background thread. Logging commands lets you replay them after a crash โ this is literally how database transaction logs work. Macro recording captures a sequence of commands to replay. Job queues in distributed systems โ where a worker picks up jobs from a queue โ are Commands.โ
โTemplate Method defines the skeleton of an algorithm in a base class, deferring some steps to subclasses. The base class controls the overall flow โ the ORDER of steps โ while subclasses provide specific implementations of individual steps. Example: a DataMiner base class has a mine() method that calls extractData(), parseData(), analyzeData(), and report() in sequence. This sequence never changes. But PDFDataMiner overrides extractData() to read PDF files, while CSVDataMiner overrides it to parse CSV. The algorithm skeleton stays in one place; variation is controlled and isolated. Chain of Responsibility passes a request along a chain of handlers. Each handler either processes the request or passes it to the next handler. Classic example: HTTP middleware. When a request arrives: AuthMiddleware checks authentication โ if invalid, reject immediately. RateLimitMiddleware checks rate limits. LoggingMiddleware logs the request. Finally the Controller processes it. Each middleware is independent, testable, and can be added or removed from the chain without touching others. This is exactly how Express.js middleware works, how Java servlet filters work, and how Django middleware works. Chain of Responsibility decouples senders and receivers and makes processing pipelines flexible.โ
โHere's your behavioral patterns decision guide. Use Observer when you have a one-to-many relationship where one event should trigger updates in multiple places โ UI updates, notifications, audit logging. Use Strategy when you have a family of algorithms and want to switch between them without if/else chains โ payment methods, sorting algorithms, authentication strategies. Use Command when you need to encapsulate requests as objects โ especially for undo/redo functionality, job queues, or transaction logs. Use Template Method when multiple classes share the same algorithm structure but differ in specific steps โ data processing pipelines, test frameworks, report generation. Use Chain of Responsibility when you have a pipeline of handlers where each can either process or pass the request โ middleware, event handling, approval workflows. Together, the Behavioral patterns give you the vocabulary to design flexible, extensible communication between objects โ without hard-coded dependencies that make systems brittle.โ
- 1Implement Observer for a real-time stock price notification system
- 2Build Strategy pattern for a sorting algorithm selector
- 3Design a Command pattern for an undo/redo text editor
- 4Implement Chain of Responsibility for HTTP request middleware