The observer pattern for Java design patterns

Source: Internet
Author: User

Reprint Please specify source: https://www.cnblogs.com/luohanguo/p/7825656.html
1, the initial understanding of the definition of the Observer pattern:

A one-to-many dependency is defined between objects so that when an object changes state, the objects that depend on it are notified and updated automatically.

Plain English

In fact, it is the publish subscription model, the Publisher publishes the information, the Subscriber obtains the information, the subscription receives the information, does not receive the information without the subscription.

2, the pattern of the structure of Figure 3, you can see that the pattern contains four characters
    • abstract The Observer role : An abstract topic that holds all references to observer objects in a collection, each subject 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 a topic notification.
    • specific Observer role : that is, a specific topic, when the internal state of a collective theme changes, all registered observers give notice.
    • specific Observer role : The update interface required to implement the abstract observer role, while reconciling its state with the state of the drawing.
4. Examples of usage scenarios

There is a public service, the occasional release of some news, attention to the public can receive a push message, the cancellation of attention will not receive the push message.

5. The Observer mode is implemented concretely

1. Define an abstract Viewer interface

Package com.jstao.observer;/*** * Abstract by Observer interface * Declares add, delete, notify Observer method * @author Jstao * */public interface observerable {        Publ IC void Registerobserver (Observer o);    public void Removeobserver (Observer o);    public void Notifyobserver ();    }

2. Define an abstract observer interface

Package com.jstao.observer;/*** * Abstract Viewer * defines an update () method that, when the observer invokes the Notifyobservers () method, the Observer's update () method is recalled. * @author Jstao * */public interface Observer {public    void update (String message);

3, the definition of the observer, the implementation of the Observerable interface, the Observerable interface of the three methods of implementation, and a list set to save the registered observer, and so on need to notify the Observer, the collection can be traversed.

Package Com.jstao.observer;import Java.util.arraylist;import java.util.list;/** * The Observer, the public service * implements the Observerable interface, The three methods of the Observerable interface are implemented in detail * @author Jstao * */public class Wechatserver implements Observerable {//Note the pan of this list collection    Observer interface, Design principle: interface-oriented programming rather than the implementation of programming private list<observer> List;        Private String message;    Public Wechatserver () {list = new arraylist<observer> ();    } @Override public void Registerobserver (Observer o) {list.add (o);    } @Override public void Removeobserver (Observer o) {if (!list.isempty ()) List.remove (o); }//Traversal @Override public void Notifyobserver () {for (int i = 0; i < list.size (); i++) {Obser            Ver oserver = list.get (i);        Oserver.update (message);        }} public void Setinfomation (String s) {this.message = s;        SYSTEM.OUT.PRINTLN ("Service Update message:" + s);    Message Update, notify all observers notifyobserver (); }} 

4, the specific observer, the public number of the specific observer for the user

Package com.jstao.observer;/** * Viewer * Implements the Update method * @author Jstao * */public class User implements observer {    private String name;    private String message;        Public User (String name) {        this.name = name;    }        @Override public    void Update (String message) {        this.message = message;        Read ();    }        public void Read () {        System.out.println (name + "received push message:" + message);}    }

5. Write a test class

First registered three users, Zhangsan, LiSi, Wangwu. The public has released a message, "PHP is the best language in the world!" ", three users have received the message.

User Zhangsan See the message after quite shocked, decisive unsubscribe, then the public number and pushed a message, the user Zhangsan has not received the message, other users

It is still normal to receive push messages.

Package Com.jstao.observer;public class Test {public        static void Main (string[] args) {        Wechatserver server = new Wechatserver ();                Observer Userzhang = new User ("Zhangsan");        Observer Userli = new User ("LiSi");        Observer Userwang = new User ("Wangwu");                Server.registerobserver (Userzhang);        Server.registerobserver (Userli);        Server.registerobserver (Userwang);        Server.setinfomation ("PHP is the best language in the world!") ");                System.out.println ("----------------------------------------------");        Server.removeobserver (Userzhang);        Server.setinfomation ("Java is the best language in the world!") ");            }}

Test results:

Second, the Java comes with the Observer pattern

O thebserver object is the Observer, and theobservable object is the observer.

1. implementing the Observer pattern implementing the Observer pattern is very simple,[1] created by the Observer class, it inherits from the Java.util.Observable class;[2] Create the Observer class, which implements the Java.util.Observer interface; 
    • For the class of the person being observed:
The Observer who added it:void Addobserver (Observer o)The Addobserver () method adds the Observer object to the list of observer objects

When events in the observed are changed, the executionsetchanged ();notifyobservers ();The Setchange () method is used to set an internal flag bit indicating that the data has changed, and the Notifyobservers () method calls the update () method of all observer in the Observer object list to notify them that the data has changed. only after Setchange () is called, Notifyobservers () will call Update ().  
    • For the Observer class, the only way to implement the Observer interface update

void Update (Observable o, Object Arg)

The parameter, object arg, corresponds to an argument passed by Notifyobservers (object Arg), and when the notifyobservers () is executed, ARG is null.

    • Instance:

      

Observed by: Star-Star

Package Com.feicui.guanchazhe;

Import java.util.Observable;

public class Star extends observable{
The person being observed
Private String info;

public void Show (String info) {
This.info = info;
}

Public String GetInfo () {
return info;
}

public void get (String str) {
Setchanged ();
Notifyobservers (str);
}

}

Observer: Fs---Fans

Package Com.feicui.guanchazhe;

Import java.util.Observable;
Import Java.util.Observer;

public class Fs implements observer{

private String name;

Public Fs (String name,observable o) {
This.name=name;
O.addobserver (this);
}

Observers
@Override
public void update (Observable o, Object Arg) {
Star S = (star) o;
System.out.println (name+ "concerned" +s.getinfo () +arg);
}

}

Testing class: Test

Package Com.feicui.guanchazhe;

public class Test {

public static void Main (string[] args) {
Star star = new Star ();

FS FS = new FS ("Eastern Evil", Star);
FS FS2 = new FS ("West Poison", star);
FS FS3 = new FS ("South Emperor", star);
FS FS4 = new FS ("North Hack", star);

Star.show ("Zhang Jie");
Star.get ("New song" Wahaha ");
System.out.println ();
Star.show ("Zhang Shan");
Star.get ("The New Dance", "the Season Dance");
}

}

Test results:

The observer pattern for Java design patterns

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.