The Observer pattern (Observer) defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time. When the subject object changes in state, all observer objects are notified so that they can automatically update themselves.
For example, when a button has multiple listeners, when the button is clicked, multiple observers are notified and perform the appropriate action.
The viewer consists of four parts:
- Abstract Theme Role: Save references to all observer objects in a collection, and each abstract theme role can have any number of observers. Abstract topics provide an interface that can add and remove observer roles. Typically implemented with an abstract class or interface.
- Abstract Observer role: Define an interface for all specific observers and update yourself when you get notifications for a topic.
- Specific topic role: Notifies all registered observers when the internal state of a specific topic changes. A specific theme role is typically implemented with a subclass.
- Specific observer role: This role implements the update interfaces required by the abstract observer role in order to reconcile the state of itself with the state of the topic. If necessary, the specific observer role can save a reference to a specific topic role. Typically implemented with a subclass.
The simple implementation of the observer pattern is as follows.
Abstract Theme Roles:
Public Interface watched{ publicvoid Addwatcher ( Watcher Watcher);//Increase observer public void Removewatcher (Watcher Watcher);//move out observer public void Notifywatchers (String str);//Notify Viewer}
Abstract Observer Role:
Public Interface watcher{ publicvoid update (String str);
Specific theme roles:
Public classConcretewatchedImplementswatched{Privatelist<watcher> list =NewArraylist<watcher>(); @Override Public voidAddwatcher (Watcher Watcher) {List.add (watcher); } @Override Public voidRemovewatcher (Watcher Watcher) {list.remove (watcher); } @Override Public voidnotifywatchers (String str) { for(Watcher watcher:list) {watcher.update (str); } }}
Specific Observer roles:
Public class Implements watcher{ @Override publicvoid update (String str) { System.out.println (str);} }
Test class:
public class observertest{ public static void main (string[] args) { Watched girl = new concretewatched (); Watcher W1 = new Concretewatcher (); Watcher W2 = new Concretewatcher (); Watcher W3 = new Concretewatcher (); Girl.addwatcher (W1); Girl.addwatcher (W2); Girl.addwatcher (W3); Girl.notifywatchers ( "I ' m Happy"
Java Learning Note-Observer mode