Learning Observer Pattern
Introduction to the Observer Pattern
The observer pattern is a behavioral design pattern that notifies interested objects of an observed object’s state. It may establish a one-to-one or one-to-many relationship between objects, notifying and updating them automatically. Think of how you receive news and weather notifications or app updates on your phone — this pattern follows the same principle.
Terms often used with this pattern are:
- Observable: The object being monitored for changes. It’s sometimes known as the subject.
- Observer: The object listening for changes to the observable.
- Publish: The act of sending a message from an observable to the observers.
- Subscribe: The act of registering to listen for changes to an observable.
Advantages of the Observer Pattern
Reasons to use the observer pattern include:
- Objects are decoupled from each other.
- There’s a clean separation of concerns between entities.
- It provides a way to implement real-time functionalities in an app.
- It’s simple to implement.
- It presents a better alternative to polling an object for updates.
Disadvantages of the Observer Pattern
Some drawbacks to using the observer pattern include:
- The observer pattern breaks encapsulation as properties representing state go outside the scope of the observers.
- It’s difficult to manage disposing of observers as they may be scattered throughout the app.
- When poorly implemented, you may introduce tight coupling instead of loose coupling.
- The observer pattern increases complexity and introduces overhead.
- The order of notifications isn’t reliable.
- Built-in support for this pattern by some languages uses inheritance, which is usually dropped in favor of composition.
In the following demo, you’ll enhance your e-commerce app by implementing the observer pattern.