Observer - Harsh4999/Design-Patterns GitHub Wiki
Observer
USE
- Using observer we can notify multiple objects about state change
- The object which are intrested in knowing about state change are called as Observer's
- Its all called as publisher-subscriber design patter (pub-sub model)
- Single object will publish its state and multiple subscriber
- Object communication without tightly coupling
UML
- Subject: Interface for registering observers. Supports multiple observers it is also called as observable
- Concrete Subject: Implementation of subject, sends notification to observers when state changes
- Observers: Interface for objects that want notification when state changes
- Concrete Observers: Implementation of observers, maintains referce to concrete subject
Implementation
- Implement Listners/Observers
- Implement Subject/Observables
- In subject implementation we take care of registration and deregistration, notification and state info methods
- Observers will have an reference to Subject which they will use for notification service
- Look closely and avoid a circular update loop which may lead to infinity
- Observer can listen for changes in multiple subjects at a time. It becomes quite easy to find origincator for notification.
- Performance cost may be high depending on notification list size
- Eg: Util class Observer interface and Observable. HttpSessionListener & addListner in servlet context