Java design pattern-Observer Pattern
Observer Mode Observer
The observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves.
Composition of observer Mode
Abstract topic role: stores all references to the observer object in a collection. Each abstract topic role can have any number of observers. Abstract topic provides an interface to add and delete observer roles. It is generally implemented using an abstract class and interface.
Abstract observer role: defines an interface for all specific observers and updates themselves when receiving notifications of a topic.
Topic roles: send notifications to all registered observers when the internal status of a specific topic changes. A topic role is usually implemented using a subclass.
Specific observer role: this role implements the update interface required by the abstract observer role to coordinate its status with the status of the topic. It is usually implemented using a subclass. If necessary, a specific observer role can save a reference pointing to a specific topic role.
The following is the sample code:
/*** Abstract topic role ** @ author dream **/public interface Watched {public void addWatcher (Watcher watcher); public void remWatcher (Watcher watcher ); public void policywatcher (String str );}
/*** Abstract observer role ** @ author dream **/public interface Watcher {public void update (String str );}
/*** Specific topic role ** @ author dream **/public class SpecifcWatched implements Watched {public List
List = new ArrayList
(); @ 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 policywatcher (String str) {// TODO Auto-generated method stubint len = list. size (); for (int t = 0; t
/*** Specific observer 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 observer mode ** @ author dream **/public class Test {public static void main (String [] args) {Watched watched = new SpecifcWatched (); watched. addWatcher (new SpecifcWatcher (zhangsan); // Add the observer watched. addWatcher (new SpecifcWatcher (lisi); watched. notifyWatcher (update); // notifies the observer of changes }}
Test results: