Simply put, the Observer pattern defines a one-to-many dependency that allows one or more observer objects to monitor a subject object. Changes in the state of such a Subject object can inform all those observer objects that depend on the object so that the observer objects can be automatically updated.
Structure of the Observer pattern
The Observer (Observer) pattern is an object's behavioral pattern, also known as the Publish-subscribe (publish/subscribe) mode, model-view (model/view) mode, source-listener (source/ Listener) mode or dependent (dependents) mode.
The class diagram structure of this pattern is as follows:
Figure 1, the static structure of the observer pattern can be seen clearly from the class diagram.
The following roles are available in the Observer mode:
. Abstract theme (Subject) role: A theme role keeps references to all the Observer objects in a list, and each topic can have any number of observers. A theme provides an interface to add or revoke an observer object, and the subject role is also called the Abstract Observer (observable) role;
Figure 2, the abstract theme role, sometimes called the abstract observer role, can be implemented with an abstract class or an interface, and the use of a specific class implementation is not excluded in specific cases.