Java Implementation Viewer (Observer) mode

Source: Internet
Author: User

1. Java comes with the implementation

Class diagram


/** * Observation target inherits from Java.util.Observable * @author Stone * */public class Updateobservable extends Observable {private int data ;p ublic updateobservable (Observer Observer) {addobserver (Observer);/* * Add other Observer */}public int getData () {retur n Data;} public void SetData (int data) {if (data! = this.data) {this.data = data;setchanged ();//tag changed, only marked before notification to Notifyobservers () ; Notification}} @Overridepublic synchronized void Addobserver (Observer o) {super.addobserver (o);} @Overridepublic synchronized void Deleteobserver (Observer o) {super.deleteobserver (o);} @Overridepublic void Notifyobservers () {super.notifyobservers ();} @Overridepublic void Notifyobservers (Object arg) {super.notifyobservers (arg);} @Overridepublic synchronized void Deleteobservers () {super.deleteobservers ();} @Overrideprotected synchronized void setchanged () {super.setchanged ();} @Overrideprotected synchronized void clearchanged () {super.clearchanged ();} @Overridepublic synchronized Boolean hasChanged () {return super.haschanged ();} @Overridepublic synchronized int countobservers () {return super.countobservers ();}} 

/** * Viewer Implements Java.util.Observer interface * @author Stone * */public class Updateobserver implements Observer {@Overridepublic void Update (Observable o, Object Arg) {System.out.println ("Notification of data Changes received:"); if (o instanceof updateobservable) { Updateobservable UO = (updateobservable) o; System.out.print ("Data changed to:" + uo.getdata ());}}}

2. Custom Observation Models

Class diagram


/** * Abstract Observer Observer * Observation UPDATE * @author stone * */public interface Iwatcher {/* * Notification Interface: * 1. Simple notification * 2. The observer needs the data of the target change, then the target can be As parameters, see Java Observer and observable *///void update (iwatched watched); void update ();}

/** * Abstract Target Subject * Provides an interface for registering and deleting observer objects, and an interface that notifies the observer to observe and the interface of the  Target's own observed business * @author stone * */public interface IWATCHEDSUBJ ECT {public void Add (Iwatcher watch);p ublic void Remove (Iwatcher watch);p ublic void Notifywhatchers ();p ublic void Update ( );//interface to be observed for business changes}

/** * Specific Observer concrete Observer *  * @author Stone * */public class Updatewatcher implements Iwatcher {@Overridepublic Voi D update () {System.out.println (this + "observed: Target has been updated");}}

/** * Specific target role concrete Subject * @author Stone * */public class Updatewatchedsubject implements Iwatchedsubject {private Lis T<iwatcher> list;public Updatewatchedsubject () {this.list = new arraylist<iwatcher> ();} @Overridepublic void Add (Iwatcher watch) {this.list.add (watch);} @Overridepublic void Remove (Iwatcher watch) {this.list.remove (watch);} @Overridepublic void Notifywhatchers () {for (Iwatcher watcher:list) {watcher.update ()}} @Overridepublic void Update () {SYSTEM.OUT.PRINTLN ("Target update ...."); Notifywhatchers ();}}

Listeners are an implementation of the viewer

Class diagram


/** * Monitor user after registration * @author Stone * */public interface Iregisterlistener {void onregistered ();}

/** * Monitor when the user logs on * @author stone * */public interface Iloginlistener {void onlogined ();}

/* * Listener is an implementation of the observer pattern * Some need to listen on the business interface to add listeners, invoke the appropriate method of listener, implement monitoring */public class User {public void register (Iregisterlistener Regi ster) {/* * do ... register */system.out.println ("Registering in ...");//After registration register.onregistered ();} public void Login (Iloginlistener login) {/* * do ... login */system.out.println ("Logging in ...");//Login after login.onlogined ();}}

/** * Observer (Observer) mode behavioral pattern * The   Observer pattern defines a one-to-many dependency that allows multiple observer objects to observe a target object at the same time. *   when the target object changes in state, all observer objects are notified, allowing them to automatically update themselves * the interface required to add, remove, notify observers in the target object *    @author stone */public class Test {public static void Main (string[] args) {/* * Use Java-brought observer interface and observable class */updateobservable observable = new UPDATEOBSERVABL E (New Updateobserver ()); Observable.setdata (99); System.out.println (""); System.out.println ("");/* * Custom Observer model */iwatchedsubject watched = new Updatewatchedsubject (); Watched.add (new Updatewatcher ()); Watched.add (new Updatewatcher ()); Watched.update (); System.out.println ("");/* Sub-mode-listener */user user = new User (); User.register (new Iregisterlistener () {@Overridepublic void Onregistered () {System.out.println ("Supervisor hears registration ... ");}}); User.login (New Iloginlistener () {@Overridepublic void onlogined () {System.out.println ("After you hear the login ... ");}});}}

Print

Notification of data changes received: Data changed to: 99 Target update .... [Email protected] observed: The target has been updated [email protected] observed: The target has been updated in the registration ... After hearing the registration ... Logging in ... After hearing the login ...




Java Implementation Viewer (Observer) mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.