Java Watcher pattern

Source: Internet
Author: User

The Observer pattern is also known as the Publish/subscribe (publish/subscribe) pattern, so we can use the subscription of newspaper periodicals to illustrate the image:

The newspaper party is responsible for publishing the newspaper.

You have subscribed to the newspaper, so long as the newspaper publishes a new newspaper, you will be notified, or sent to your hands.

If you don't want to read the newspaper again, you can unsubscribe so that the newspaper will not let you know when it publishes a new newspaper.

Understanding the above concepts, you can understand the observer pattern, the observer pattern has the subject (SUBJECT) and the Observer (Observer), respectively, the newspaper and Subscribers (you). The Observer pattern defines a one-to-many dependency between objects, so that when the state of the "a" is changed, It relies on the "many" side will be notified and automatically updated.:

Structure diagram of this pattern

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.

Code implementation:

1. Define an abstract Viewer interface

/**@author*/Publicinterface  observerable {         publicvoid  registerobserver (Observer o);      Public void removeobserver (Observer o);      Public void notifyobserver ();    }

2. Define an abstract observer interface

/**@author*/Publicinterface  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.

/*** The observed, that is, the public service * implements the Observerable interface, the implementation of the three methods of the Observerable interface *@authorJstao **/ Public classWechatserverImplementsobserverable {//Note that the generic parameter of this list collection is the Observer interface, Design principle: interface-oriented programming rather than implementation-oriented programming    PrivateList<observer>list; PrivateString message;  Publicwechatserver () {list=NewArraylist<observer>(); } @Override Public voidregisterobserver (Observer o) {list.add (o); } @Override Public voidremoveobserver (Observer o) {if(!list.isempty ()) List.remove (o); }    //Traverse@Override Public voidNotifyobserver () { for(inti = 0; I < list.size (); i++) {Observer oserver=List.get (i);        Oserver.update (message); }    }         Public voidsetinfomation (String s) { This. Message =s; System.out.println ("Service Update message:" +s); //message Update, notify all observersNotifyobserver (); }}

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

/*** Viewer * Implements Update method *@authorJstao **/ Public classUserImplementsObserver {PrivateString name; PrivateString message;  PublicUser (String name) { This. Name =name; } @Override Public voidUpdate (String message) { This. Message =message;    Read (); }         Public voidRead () {System.out.println (name+ "Receive 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. The 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, the other users can still receive the push message normally.

 Public classTest { Public Static voidMain (string[] args) {wechatserver server=NewWechatserver (); Observer Userzhang=NewUser ("Zhangsan"); Observer Userli=NewUser ("LiSi"); Observer Userwang=NewUser ("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!" "); }}

The benefits of the Observer pattern:

The Observer pattern provides an object design that allows the coupling between the subject and the observer to drop very low, for what? For all of the observer, the subject only knows that the observer implements the observer interface, and does not require the observer to specify who the class is, what to do, or other details.

In this way, because of loose coupling, changing the subject or one of the observers does not affect the other party, as long as the interface between them is still adhered to, it is free to change it.

Reducing the coupling between the objects is also a very important principle in the design of the face-setting object.

Java Watcher pattern

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.