The Subject class is a key part of the Observer Pattern. It maintains a list of observers and ensures that they are notified whenever there is a change in the state.
The Subject class allows multiple observers to register themselves using the attach() method. When the state changes, the notifyAllObservers() method is called to inform all attached observers.
- getState() - Returns the current state of the subject.
- setState(int state) - Updates the state and calls
notifyAllObservers(). - attach(Observer observer) - Adds an observer to the list.
- detach(Observer observer) - Removes an observer from the list so it no longer receives updates.
- notifyAllObservers() - Iterates through the observer list and calls their
update()method.
This pattern is useful when multiple objects need to stay updated with changes in another object’s state. It promotes loose coupling, as the subject does not need to know details about its observers.
The Observer class is an essential part of the Observer Pattern. It represents an entity that listens for changes in the Subject and updates itself accordingly.
Observers register themselves with a Subject. When the subject’s state changes, it calls the update() method on all registered observers, allowing them to react accordingly.
- update() - This method is called when the subject's state changes. Each observer implements this method differently to handle the update as needed.
- Constructor - Observers typically receive a reference to the subject during creation so they can register themselves.
The Observer Pattern is useful for creating a one-to-many dependency between objects. It ensures that changes in the subject are automatically reflected in all observers, keeping them synchronized.
yes the notification message for the length more then 160 character in the class and the giving warning has been added.