Observer Pattern: defines a one-to-many dependency between objects, so that when an object changes state, all its dependents are notified and updated.
The subject and the observer define a one-to-many relationship, and the observer relies on the subject. When the state of the subject object changes, the observer is notified. Follow the instructions to inform the viewer.
First, involved in the role: topic interface , Observer interface , specific topics , specific observers.
Pros: The subject is the object that really owns the data, the observer is the subject of the dependency, in the data changes and new when this is more than multiple objects control the same data, can be more clean oo design.
Cons: Not all observers need this data, they may need only a subset of them, but they receive a bunch of data. (see this pattern in the JDK, which provides support for proactively fetching data in a getter approach)
Ii. Observer patterns in the JDK
The JDK provides support for the observer pattern. Subject class Observable, the specific theme class can inherit the implementation class Observable class in the JDK. Specific observers can implement the Observer interface Observer interface in the JDK.
topic notifies the Observer : inherits the subject interface of the jdkobservable, notifying the Observer object step.
(1) First call the Setchanged () method in observable. Tag status has changed
(2) Call Notifyobservers () or Notifyobservers (ARG) (with the parameter method to push the specified parameter).
Observer Mode (OBSERVER)