The observer pattern for Java design patterns

Source: Internet
Author: User

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; /**  @author*/Publicinterface  observerable        {  Public void registerobserver (Observer o);      Public void removeobserver (Observer o);      Public void notifyobserver ();    }

2. Define an abstract observer interface

 Package Com.jstao.observer; /**  @author*/Publicinterface  Observer    {  publicvoid  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.

 PackageCom.jstao.observer;Importjava.util.ArrayList;Importjava.util.List;/*** 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

 PackageCom.jstao.observer;/*** 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.

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.

 PackageCom.jstao.observer; 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!" "); }}

Test results:

6. Summary
    • This pattern is loosely coupled. Change the subject or the observer, and the other party will not be affected by the image.
    • There is also a self-contained observer pattern in the JDK. But the observer is a class, not an interface, which limits its ability to reuse.
    • You can also see the shadow of the observer pattern in JavaBean and swing.

Stunned, wrote a summary of the morning blog, to release the time off the network, the heart cooled a section. Fortunately, after the browser has a cache, you can restore, near misses, remember to always save the draft!

The observer pattern for Java design patterns

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.