The Observer Pattern
Prodip Datta
Software Engineer @ SELISE Digital Platforms | Passionate about Building User-Friendly Applications | C# | .NET CORE | Mongo | Angular
Observer pattern
- The Observer Pattern defines a one-to-many dependency between objects so that all of its dependents are notified and updated automatically when one object changes state.
More generally, The Observer Pattern defines a one-to-many relationship between a set of objects.
When the state of one object changes, all of its dependents are notified.
Meet the observer pattern
You know how newspaper or magazine subscriptions work:
Publisher + Subscribers = Observer Pattern
If you understand newspaper subscriptions, you pretty much understand the Observer Pattern, only we call the publisher the SUBJECT and the subscribers the OBSERVERS.
The Power of Loose Coupling
When two objects are loosely coupled, they can interact, but they typically have very little knowledge of each other. The Observer Pattern is a very great example of loose coupling.
领英推荐
Let's walk through all the ways the pattern achieves loose coupling:
Loosely coupled designs allow us to build flexible Object-Oriented (OO) systems that can handle change because they minimize the interdependency between objects.
So, by learning The Observer Patterns, we have added a few things to our Object-Oriented toolbox:
- Encapsulate what varies
- Favor composition over inheritance
- Program to interface, not implementations
- Strive for loosely coupled designs between objects that interact
- The Observer Pattern
an example code where I implemented the Observer Pattern can be found here: ObserverPatternExample