Observer Pattern
Observer Pattern
An Observer Pattern says that "just define a one-to-one dependency so that when one object changes state, all its dependents are notified and updated automatically".
The Memento pattern is also known as Dependents or Publish-Subscribe.
Benefits:
- It describes the coupling between the objects and the observer. Loosely coupled objects are flexible with changing requirements. Here loose coupling means that the interacting objects should have less information about each other.Observer pattern provides this loose coupling as:
- Subject only knows that observer implement Observer interface.Nothing more.
- There is no need to modify Subject to add or remove observers.
- We can reuse subject and observer classes independently of each other.
- It provides the support for broadcast-type communication.
Disadvantage:
- Memory leaks caused by Lapsed listener problem because of explicit register and unregistering of observers.
Usage:
- You should consider using this pattern in your application when multiple objects are dependent on the state of one object as it provides a neat and well tested design for the same.
- When the framework we writes and needs to be enhanced in future with new observers with minimal changes.
Java Implementation:
Output:
Average Score Display: Run Rate: 8.823529 PredictedScore: 441 Current Score Display: Runs: 90 Wickets:2 Overs: 10.2 Current Score Display: Runs: 90 Wickets:2 Overs: 10.2
Reference: https://www.geeksforgeeks.org/observer-pattern-set-2-implementation/
Comments
Post a Comment