What is it?
It ensures that when on object changes state, all its dependencies are notified and updated automatically. It defines a one-to-many dependency.
The key objects in this pattern are the subject and the observer. When there is a change in state with the subject, all the observers are notified. In response to the change, the observer will synchronize with the subject’s state.
When to use the observer pattern?
- When change to one object requires change to another and there is no knowledge of how many objects need to be changed.
- When you don’t want any tightly coupled objects.
Steps to create an Observer pattern
- Create a Subject and Observer patterns. The subject will register, unregister or notify the observers of any changes occurring during runtime. The observer will have the method/methods of variables that need to be updated or changed.
- Create a class that implements the subject.
- Create an array list in this class containing all the observers.
- Create the methods for registering and unregistering the observers as well as notifying the observers of any change occurring.
- Create a class that implements the observer.
- In this class, make updates to the variables that need to be changed.
- Use a main class where you can make changes to the variables dynamically. These values will be passed to the method implementing the subject class where the values will be set. When these values are set, notify the observers of this change so the change could take place.
References