Observer Mode Observer
The Observer pattern 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, allowing them to automatically update themselves.
The composition of the Observer pattern
Abstract Theme role: All references to observer objects are saved 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. It is generally implemented with an abstract class and 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. Typically implemented with a subclass. If necessary, the specific observer role can save a reference to a specific topic role.
The following is the sample code:
/** * Abstract Theme characters * @author Dream * */public interface watched {public void Addwatcher (Watcher watcher);p ublic void REMWATC Her (watcher watcher);p ublic void Notifywatcher (String str);}
/** * Abstract Viewer role * @author Dream * */public interface Watcher {public void update (String str);
/** * Specific Theme characters * @author Dream * */public class Specifcwatched implements watched {public list<watcher> List = new ARR Aylist<watcher> (); @Overridepublic void Addwatcher (Watcher Watcher) {//TODO auto-generated method Stublist.add ( Watcher);} @Overridepublic void Remwatcher (Watcher Watcher) {//TODO auto-generated method Stublist.remove (watcher);} @Overridepublic void Notifywatcher (String str) {//TODO auto-generated method Stubint len = List.size (); for (int t=0; t< Len ++t) {Watcher Watcher = List.get (t); Watcher.update ("Update");}}}
/** * Specific Viewer role * @author Dream * */public class Specifcwatcher implements Watcher{string name;public Specifcwatcher (String Name) {this.name = name;} @Overridepublic void Update (String str) {//TODO auto-generated method StubSystem.out.println (name+ ":" +str);}}
Test class:
/** * Test Viewer mode * @author Dream * */public class Test {public static void main (string[] args) {watched watched = new specifc Watched (); Watched.addwatcher (New Specifcwatcher ("Zhangsan")); Add observer Watched.addwatcher (New Specifcwatcher ("Lisi")); Watched.notifywatcher ("Update"); Notify Viewer of Changes}}
Test results:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Design Pattern-viewer mode