An observer design pattern is a software design pattern that consists of a subject. This subject has the list of observers and methods to take action on the observers. The main significance of the design pattern is that it will notify for any state change events. All the dependents of one object will be notified and updated automatically during any change. There are a subject and an observer in this design pattern. The main concepts are:
- The subject and the observers are the objects involved in this design pattern.
- One many relation exists between the subject(1) and the observer(M).
- The observers need to register or subscribe to the subject to get notified about any state change.
- Unsubscribe functionality is also there. If you unsubscribe, you will not get updated data or notifications.
- If any update or change is there in the object, then all the subscribed users will get notified and updated.
- Observers are dependent entities here. It depends on the subject to provide them with data.
- The subject has ObserverCollection which is the list of all the subscribed observers.
- The subject has different methods such as registerObserver(), unregisterObserver() and notifyObserver().
- registerObserver() will add the new observer. unregisterObserver() will remove observers.
- notifyObserver() is used to notify the dependents that the observers are changed and new data should be supplied.
- The consumer or who needs data should implement observer interface.
- The notify() method is part of observer interface which will define what action to perform when data is provided by the subject.
- The subject and the observer are loosely coupled. The subject only knows that you subscribed to it. That's why it provides the data. It has no underlying concerns like who are the observers, how they behave, etc. For the subject, observers are only subscribers.
Example to understand the design pattern
Suppose we have a play arena where we have different games and activities available.
- The manager in the stadium is the Subject here that will have the list of all the games, activities.
- If any person who is interested in games and activities to take membership or register with the play arena, then he/she has to take the membership for it. It is defined as subscribing.
- The subscribed members will get all the notifications, any changes or any kind of update in games or activities. If any new activity is launched, the members will be notified.
- If the person unsubscribes from the membership, then they will not get updated information about games and activities.
- The relationship here between the manager and the member of the play arena is loosely coupled. For the subject, the people are just members who have paid money and bought the membership.
- The subject and the observer are different entities.