Design patterns go through---observer mode (bottom)

Source: Internet
Author: User

In the previous section we explained some of the knowledge of the observer pattern and customized the classic code of the Observer Pattern, (Teleport: Design mode go through--observer mode (above))

This article briefly introduces the observer Pattern implementation code that comes with the JDK.

For the Observer pattern, a observer Interface (Viewer), a observable class (Subject object) is provided in the JDK.

NOTE: The Observer is also known as the Subject object, the target object.

Specifically, we look at the source code.

1. Observer interface

public interface Observer {    /**     * This method is called whenever the observed *object is changed.      *当被观察者发生变化时,该方法将会被调用     * @param   o     the observable object.     * @param   arg   an argument passed to the <code>notifyObservers</code>     *                 method.     */    void update(Observable o, Object arg);}

This interface is equivalent to the Observer , which has an update (Observable O, Object arg) method, and the Observable parameter refers to the subject Object , which indicates that the observer belongs to which subject object.

The arg parameter can be any object, and the data object can be passed to the ARG parameter if the subject object wants to pass any data to the observer when it sends the notification.

2. Subject Object Class (there are a bit more methods, I won't explain it in English)

The subject object can be interface, abstract class, concrete class, we say//generally use abstract class, but the JDK used here is the specific class public class Observable {//tag the state of the subject object is changed private Boolean changed =    False    Storing the Observer collection, the reason for using vectors instead of ArrayList//is that vectors are thread-safe private vector<observer> obs;    Public Observable () {obs = new vector<> (); }//Add an observer public synchronized void Addobserver (Observer o) {if (o = = null) throw new Nullpointe        Rexception ();        if (!obs.contains (o)) {obs.addelement (o);    }}//delete an observer public synchronized void Deleteobserver (Observer o) {obs.removeelement (o);    }//Marks whether the state of the object sent changed protected synchronized void setchanged () {changed = TRUE;    }//Indicates that the object will no longer change, or that it has been notified//all observers protected synchronized void clearchanged () {changed = FALSE; }//The test object has changed.    When and only if this object has recently//called the Setchange () method public synchronized Boolean hasChanged () {return changed; }//If the Haschanged () method indicates that the object sent a change,//notifies all observers, and calls ClearchangeThe D () method//Indicates that this object no longer changes public void Notifyobservers () {notifyobservers (null); }//Is the same as the method with the same name without parameters above, except that if the arg parameter of the square//method can accept the subject object to pass the observer's data object public void Notifyobservers (object arg) {//Temporary Save        There are observers object[] arrlocal;            Synchronized (this) {if (!changed) return;            arrlocal = Obs.toarray ();        Clearchanged ();    } for (int i = arrlocal.length-1; i>=0; i--) ((Observer) arrlocal[i]). Update (this, ARG);    }//Delete all observers public synchronized void Deleteobservers () {obs.removeallelements ();    }//Returns the number of observers public synchronized int Countobservers () {return obs.size (); }}

The specific class observable equivalent to the subject Object , the main function of the implementation is to notify the observer when their state sends a change, the observer, according to the notification, the Update method to respond accordingly.

Simply write a demo test.

public class Test {public static void main (string[] args) {//Create a Subject object Animalsubject Animalsubject = new        Animalsubject ();        Animalsubject.addobserver (New Dogobsever ());        Animalsubject.addobserver (New Lionobsever ());        The state changes animalsubject.setchanged ();    Inform the Observer Animalsubject.notifyobservers (); }}//Animal Theme, sub-class to facilitate the expansion of the theme of the object function class Animalsubject extends observable{///But I will not add code, methods//Do not overwrite, the above test can not call the Setchange () method//For    A convenient test, overwriting overrides under @Override protected synchronized void setchanged () {super.setchanged (); }}class Dogobsever implements observer{@Override public void update (Observable o, Object Arg) {SYSTEM.OUT.P    RINTLN ("received notification, puppy watcher is making corresponding treatment"); }}class Lionobsever implements observer{@Override public void update (Observable o, Object Arg) {System.out.    println ("Received notice, Lion Watcher is making corresponding treatment"); }}

Print results

收到通知,狮子观察者正在做出相应处理收到通知,小狗观察者正在做出相应处理

From the code above we can find that the subject object in the Observer pattern built into the JDK is a concrete class, not an abstract class or interface, and the Setchange () method is also protected (defined as protected), which means that the method is called in another class. Then we must inherit overrides in the subclass overrides the method. Obviously, I think it's unfriendly .....

Perhaps this is why the built-in observer pattern of the JDK is rarely used, and it is generally the custom observer pattern.

I hope you can write this code, you may encounter some problems you did not think of.

Finish

Pay attention to the public my number: hard yards of farmers , get more original articles, backstage reply gift pack to send you a list of popular resources in the present package. And thanks for introducing the article to more people who need it.

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.