Observer
28 Aug 2022Observer
Defines a one to many dependency between objects so that when one object changes state, all it's dependents are notified and updated automatically.
Also Known as
Dpendents, Publish-Subscribe
Applicability
Use visitor pattern when:
- When ans 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.
Structure
Participants
- Subject: knows it's observers. Any member of Observer objects may observe a subject, provides an interface for attaching and detaching Observer objects.
- Observer: defines an updating interface for objects that should be notified of changes in a subject.
- ConcreteSubject: stores state of interest to ConcreteObserver objects, sends a notification to it's observers when it's state changes.
- ConcreteObserver: maintains a reference to a ConcreteSubject object, stores state that should stay consistent with the subject's, implements the Observer updating interface to keep it's state consistent with the subject's.
Collaborations
- ConcreteSubject notifies it's observers whenever a change occurs that could make it's observer's state inconsistent with it's own.
- After being informed of a change in concrete subject, a ConcreteObserver object may query the subject for information.
Sample Code
Related Patterns
- Mediator: By encapsulating complex update semantics, the ChangeManager acts as mediator between subjects and observers.
- Singleton: The ChangeManager may use the Singleton pattern to make it unique and globally accessible.