The Observer defines a one to many relationship, so that when one object changes state, the others are notified and updated automatically. Some auctions demonstrate this pattern. Each bidder possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the bidding, and “observes” when a paddle is raised to accept the bid. The acceptance of the bid changes the bid price, which is broadcast to all of the bidders in the form of a new bid
Intent
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Alternative Name:
Dependents, Publish-Subscribe
Problem:
How to handle a common side-effect (i.e. need to maintain consistency between related object)of partitioning a system into a collection of cooperating classes with out making the classes tightly coupled , – which in turn makes classes less reusable.
Solution:
The observer pattern describes how to establish these relationships. The key objects in this pattern are subject and observer.
– A subject may have any number of dependent observer.
– All observers are notified whenever the subject undergoes a change in state.
– In response, each observer will query the subject to synchronize its state with the subject’s state.
Applicability
Use the Observer pattern in any of the following situations:
- When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
- When a change to one object requires changing others, and you don’t know how many objects need to be changed.
- When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don’t want these objects tightly coupled.
Consequences
- Abstract coupling between Subject and Observer
- Support for broadcast communication.
- Unexpected updates.
Recommended Books
Leave a Reply