Behavioral Patterns (Observer & Strategy)
Learn how to manage object responsibilities and communication effectively using the Observer and Strategy patterns.
Learning Goals
- Design event-driven systems using the Observer pattern.
- Implement interchangeable algorithms using the Strategy pattern.
- Analyze when to use behavioral patterns to reduce coupling in complex logic.
Managing Object Communication
Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects. They don't just describe patterns of objects or classes but also the patterns of communication between them.
1. The Observer Pattern
The Observer pattern defines a one-to-many dependency between objects so that when one object (the Subject) changes state, all its dependents (Observers) are notified and updated automatically.
Real-world analogy: A newspaper subscription. When the publisher releases a new issue, all subscribers receive a copy.
Why use it? When a change to one object requires changing others, and you don't know how many objects need to be changed or who they are.
Implementing an Event Bus (Observer)
- 1Step 1
Create an
IObserverinterface with anupdate(message)method. Any class that wants to listen for events must implement this. - 2Step 2
The
Subjectclass maintains a private list of observers. It provides methods likesubscribe(observer)andunsubscribe(observer). - 3Step 3
Add a
notifyObservers(message)method to the Subject. This method iterates through the list of observers and callsupdate()on each one. - 4Step 4
When a state change occurs in the Subject (e.g., a new order is placed), it calls
notifyObservers(). All registered listeners—likeEmailService,InventoryService, andSmsService—react independently.
2. The Strategy Pattern
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Visualizing Strategy
Why use it? When you have many related classes that differ only in their behavior, or when you need different variants of an algorithm.
Knowledge Check
Which behavioral pattern is best for implementing a 'Subscription' or 'Event Listener' model?