Observer mode of behavioral pattern

Source: Internet
Author: User

Observer pattern (also known as publish-subscribe mode, model-view mode, source-listener mode, or slave mode)

In the Observer pattern, a target object manages the observer object that relies on it, and proactively notifies itself when its state changes.

Application Scenarios

Auctions can be considered as one of the observer patterns, and each bidder can bid. When the auctioneer began the auction, he observed whether there was a sign to raise the bid. Each acceptance of a new bid changes the current price of the auction and broadcasts it to all bidders.

Applications in the JDK

    • Java.util.EventListener
    • Javax.servlet.http.HttpSessionBindingListener
    • Javax.servlet.http.HttpSessionAttributeListener
    • Javax.faces.event.PhaseListener

Participating roles

Abstract Theme (Subject):

Abstract topics provide an interface that can add and remove observer objects;
Subject save references to all observer objects in a collection, each subject can have any number of observers;

Specific topics (ConcreteSubject):
Store the state, which should be consistent with the state of the target;
Deposit the relevant state into the specific observer object;
Give notice to all registered observers when the internal state of the specific subject changes;
Implements the Observer update interface to align its state with the state of the target.

Abstract Observer (Observer):
Define an interface for all specific observers and update yourself when you get a topic notification.

Specific observer (Concreteobserver):
Implements the update interface required by the abstract observer role in order to reconcile the state of itself with the subject state.

Class diagram of the Observer pattern

The intent of the observer pattern is to define a one-to-many dependency between objects, an object state change, and other associated objects are notified and automatically updated.

Observer Pattern Instances

In this instance, the observer is able to register for this topic, and any changes to the content submitted on this topic will notify all the observers who are registered.

Subject Abstract Topics:

Public interface Subject {//Registered observer public void Attach (Observer obs);//Remove observer public void Detach (Observer obs);//Notify Observer public void Noticeobservers ();//Get update information for the topic public String getUpdate ();}

  

Observer abstract Subscribers:

Public interface Observer {/** * Gets theme changes, triggered by Observer */public void Update ();/** set Subject Object */public void Setsubject (Subject sbj) ;}

  

ConcreteSubject Specific topics:

public class ConcreteSubject implements Subject{private String message;//passed message body Private boolean changed;//message status ID// Store registered observers collection private list<observer> Observers;public ConcreteSubject () {this.observers=new arraylist<observer > ();} /** * Here the subject can be subject to subscription, the specific relationship between the teacher-students, etc. */@Overridepublic void Attach (Observer obs) {if (obs==null) throw new NullPointerException ("Null Observer"), if (!observers.contains (OBS)) Observers.add (OBS);} @Overridepublic void Detach (Observer obs) {observers.remove (OBS);} @Overridepublic void Noticeobservers () {list<observer> temp=null;/** * Prevents the observer from receiving a subscription to a message previously sent by the Observer */synchronized ( Concretesubject.class) {if (!changed) return;temp=new arraylist<> (this.observers); this.changed=false;} for (Observer obs:temp) {/** method to invoke the Observer */obs.update ();}} @Overridepublic String getUpdate () {return this.message;} public void PostMessage (String msg) {THIS.MESSAGE=MSG;THIS.CHANGED=TRUE;//Notification to observer Noticeobservers ();}}

  

Concreteobserver specific observers:

public class Concreteobserver implements observer{//here to label different observers private string name;//message result field private String result;// Set Theme Private Subject subject;public concreteobserver (String name) {this.name=name;} @Overridepublic void Update () {/** Gets the message from the topic Update */result=subject.getupdate ();/** processing message */system.out.println (name+ "Get Message "+result);} Set the theme @overridepublic void Setsubject (Subject sbj) {this.subject=sbj;}}

Publish-Subscribe instance:

public class Obclient {public static void main (string[] args) {ConcreteSubject sbj=new ConcreteSubject (); Concreteobserver obs1=new concreteobserver ("OBS1"); Concreteobserver obs2=new concreteobserver ("OBS2"); Concreteobserver obs3=new concreteobserver ("Obs3"),/** registered to theme */sbj.attach (OBS1); Sbj.attach (OBS2); Sbj.attach (OBS3) ;/** set the Observed object */obs1.setsubject (SBJ); Obs2.setsubject (SBJ); Obs3.setsubject (SBJ);/** Send Message */sbj.postmessage ("Hello World! ");}}

Test results:

Reference:

Example of observer patterns in Java tutorial

Observer mode (OBSERVER) Parsing example

Wikipedia • Viewer mode

Observer mode of behavioral 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.