Design Pattern-Observer Pattern

Source: Internet
Author: User
First, what is the observer mode? The observer mode refers to a situation where multiple objects know the changes of data in an object. For example, almost all colleges and universities now have part-time center for college students, that is, part-time intermediary, the part-time center notifies all members of the part-time information every day. This is an observer model. Here, members are also observers. The part-time center is the observer, also known as the topic. The observer mode structure includes four roles: 1. Topic: a topic is an interface that specifies the implementation method of a specific topic, for example, you can add or delete an observer and notify the observer to update the data. 2. Observer: the observer is also an interface that specifies the methods used by the observer to update data. 3. Specific topic: a specific topic is a class that implements the topic interface. This class contains data that will change frequently and there is also a set that stores the reference of the observer. 4. Specific observer: a specific observer is a class that implements the observer interface. A specific observer contains a topic interface variable that can be referenced by a specific topic, so that a specific observer can add his/her reference to a specific topic set and make himself/herself an observer, you can also delete a topic from its collection so that it is no longer its observer. In the example of the previous part-time center, the part-time center is a specific topic. It can update various part-time information and notify its members. Of course, it can also add and delete members. A member is an observer who pays attention to part-time center information and can receive updates from the part-time center in a timely manner. The Code is as follows: 1. Topic
package com.observer;public interface Subject {    void addObserver(Observer o);    void deleteObserver(Observer o);    void notifyObservers();}

2. Specific subject

Package COM. observer; import Java. util. arraylist; public class seekjobcenter implements subject {string mess; Boolean changed; arraylist <observer> personlist; Public seekjobcenter () {personlist = new arraylist <observer> (); mess = ""; changed = false;} // Add the public void addobserver (Observer O) {If (! (Personlist. contains (O) {personlist. add (o) ;}}// Delete public void deleteobserver (Observer O) {If (personlist. contains (O) {personlist. remove (o) ;}/// notify all job seekers of Public void policyobservers () {If (changed) {for (INT I = 0; I <personlist. size (); I ++) {observer o = personlist. get (I); O. heartelephone (MESS) ;}changed = false ;}// refresh public void givenewmess (string Str) {If (Str. equals (MESS) {changed = false;} else {mess = STR; changed = true ;}}}

3. Observer

 package com.observer;  public interface Observer {    public void hearTelephone(String mess); }

  

4. Specific observers in this example, there are two specific observers, one focusing on all the information of the part-time center and the other on part-time information of the "promoters" and "senders. Universitystudent. Java
Package COM. observer; import Java. io. file; import Java. io. filenotfoundexception; import Java. io. ioexception; import Java. io. randomaccessfile; public class universitystudent implements observer {subject; file myfile; Public universitystudent (subject, string filename) {This. subject = subject; subject. addobserver (this); myfile = new file (filename);} public void heartelephone (string mess) {try {randomaccessfile out = new randomaccessfile (myfile, "RW"); out. seek (Out. length (); byte [] B = mess. getbytes (); out. write (B); system. out. println ("I am a Member"); system. out. println ("My files" + myfile. getname () + "write the following content:"); system. out. println (MESS);} catch (ioexception e) {e. printstacktrace ();}}}

Universitystudent2.java

Package COM. observer; import Java. io. file; import Java. io. ioexception; import Java. io. randomaccessfile; public class universitystudent2 implements observer {subject; file myfile; Public universitystudent2 (subject, string filename) {This. subject = subject; subject. addobserver (this); myfile = new file (filename);} public void heartelephone (string mess) {try {Boolean boo = mess. contains ("promoter") | mess. contains ("poster"); If (BOO) {randomaccessfile out = new randomaccessfile (myfile, "RW"); out. seek (Out. length (); byte [] B = mess. getbytes (); out. write (B); system. out. println ("I am member 2"); system. out. println ("My files" + myfile. getname () + "write the following content:"); system. out. println (MESS) ;}} catch (ioexception e) {e. printstacktrace ();}}}

Write a test program as follows:

Package COM. observer; public class application {/*** @ Param ARGs */public static void main (string [] ARGs) {seekjobcenter center = new seekjobcenter (); universitystudent Zhanglin = new universitystudent (center, "zhanglin.txt"); universitystudent2 wanghao = new universitystudent2 (center, "wanghao.txt"); Center. givenewmess ("XX company needs 10 promoters. "); Center. policyobservers (); Center. givenewmess (" XX Company requires 8 senders. "); Center. policyobservers (); Center. givenewmess (" XX company needs nine temporary workers. "); Center. policyobservers (); Center. givenewmess (" XX company needs nine temporary workers. "); Center. policyobservers ();}}

The running result is as follows:

I am member 1
I write the following content to the file zhanglin.txt:
XX company needs 10 promoters.
I am member 2
I write the following content to the wanghao.txt file:
XX company needs 10 promoters.
I am member 1
I write the following content to the file zhanglin.txt:
XX company needs 8 senders.
I am member 2
I write the following content to the wanghao.txt file:
XX company needs 8 senders.
I am member 1
I write the following content to the file zhanglin.txt:
XX company needs nine temporary workers.

There is another way to pull data in the design mode. If this method is used, the updated information will only notify all the observers: "My information has been updated ". Specific observers can call related methods to obtain the information they need. Next, let's look at another example: a store publishes the name of the discounted product on the same day every day. Two customers are interested in the original price and the discounted price, however, one customer only relates to the name of the discounted product, while the other customer only cares about the original price and the discounted price. 1. Subject
package com.observer1;public interface Subject {    void addObserver(Observer o);    void deleteObserver(Observer o);    void notifyObservers();}

2. Specific subject

Package COM. observer1; import Java. util. arraylist; public class shopsubject implements subject {string goodsname; double oldprice, newprice; arraylist <observer> customerlist; Public shopsubject () {customerlist = new arraylist <observer> ();} public void addobserver (Observer O) {If (! (Customerlist. contains (O) {customerlist. add (o) ;}} public void deleteobserver (Observer O) {If (customerlist. contains (O) {customerlist. remove (o) ;}} public void policyobservers () {for (INT I = 0; I <customerlist. size (); I ++) {observer o = customerlist. get (I); O. update () ;}// set discount item public void setdiscountgoods (string name, double oldp, double newp) {goodsname = Name; oldprice = oldp; newprice = newp; // notify the customer after setting yyobservers ();} Public String getgoodsname () {return goodsname;} public double getoldprice () {return oldprice;} public double getnewprice () {return newprice ;}}

  

3. Observer: the data is not directly updated by a specific topic, so the update () method does not need to pass parameters.
 package com.observer1;  public interface Observer {    public void update();}

4. Specific observer

4. Specific observer: customers of the customerone object are only interested in the name of the discounted product and are not interested in other information. Customerone. Java
Package COM. observer1; public class customerone implements observer {subject; string goodsname, personname; Public customerone (subject, string personname) {This. personname = personname; this. subject = subject; subject. addobserver (this);} public void Update () {If (subject instanceof shopsubject) {goodsname = (shopsubject) subject ). getgoodsname (); system. out. println (personname + "interested only in the name of the discounted product:"); system. out. println ("the name of the discount item is:" + goodsname );}}}

  

Customers of the customertwo object are only interested in the original and discounted prices of the product, and are not interested in the product name.

Customertwo. Java'

 

Package COM. observer1; public class customertwo implements observer {subject; string personname; double oldprice, newprice; Public customertwo (subject, string personname) {This. personname = personname; this. subject = subject; subject. addobserver (this);} public void Update () {If (subject instanceof shopsubject) {oldprice = (shopsubject) subject ). getoldprice (); newprice = (shopsubject) subject ). getnewprice (); system. out. println (personname + "only interested in the original and post-discount prices of discounted products:"); system. out. println ("the original price of a discounted item is:" + oldprice); system. out. println ("discount price:" + newprice );}}}

 

Below is a test example:

Package COM. observer1; public class application {public static void main (string [] ARGs) {shopsubject shop = new shopsubject (); customerone boy = new customerone (shop, "James "); customertwo girl = new customertwo (shop, "Xiaohong"); shop. setdiscountgoods ("Photo Digital Camera", 2345.6, 2020.0); shop. setdiscountgoods ("Samsung mobile phone", 2999.0, 2499.0 );}}

The running result is:

James is only interested in the discount Product Name:
Discount Product Name: Photo Digital Camera
Xiaohong is only interested in the original and post-discount prices of discount products:
The original price of discount products is: 2345.6
Discount price: 2020.0
James is only interested in the discount Product Name:
Discount Product Name: Samsung mobile phone
Xiaohong is only interested in the original and post-discount prices of discount products:
The original price of discount products is: 2999.0
Discount price: 2499.0

 

Observer and multi-subject: the above two examples are about multiple observers under a specific topic. Another case is that a specific observer corresponds to multiple topics. When the information of any observed topic changes, the observer can be notified. When multiple topics are used, the topic should pull data. The observer interface can set the parameter type of the data update method to the topic interface type, such as update (subject ), that is, when the data of a specific topic changes, the reference will be passed to the specific observer, and then the specific observer will let the specific topic call relevant to obtain information. The following is a simple multi-topic example: The Problem description: Mr. Li plans to travel, so he needs to pay attention to the travel agency information and the weather problems in the travel area. According to the observer model, Mr. Li is a specific observer, and the weather station and travel agency are two specific topics he observes. The main code is as follows: 1. Topic
package com.observer2;public interface Subject {    void addObserver(Observer o);    void deleteObserver(Observer o);    void notifyObservers();}

2. Observer

package com.observer2;  public interface Observer {    public void update(Subject subject); }

3. Specific subject

package com.observer2;import java.util.ArrayList;public class TravelAgency implements Subject{    String tourStartTime;    String tourMess;    ArrayList<Observer> personList;    public TravelAgency() {        personList = new ArrayList<Observer>();    }    public void addObserver(Observer o) {        if(o == null){            return;        }else{            if(!(personList.contains(o))){                personList.add(o);            }        }    }    public void deleteObserver(Observer o) {        if(personList.contains(o)){            personList.remove(o);        }            }    public void notifyObservers() {        for (int i = 0; i < personList.size(); i++) {            Observer o = personList.get(i);            o.update(this);        }    }    public void giveMess(String time,String mess){        tourStartTime = time;        tourMess = mess;        notifyObservers();    }    public String getTourStartTime() {        return tourStartTime;    }    public String getTourMess() {        return tourMess;    }}

Weaherstation. Java

package com.observer2;import java.util.ArrayList;public class WeaherStation implements Subject{    String forecastTime,forcastMess;    int maxPemperature,minTemperature;    ArrayList<Observer> personList;    public WeaherStation() {        personList = new ArrayList<Observer>();    }    public void addObserver(Observer o) {        if(o == null){            return;        }else{            if(!(personList.contains(o))){                personList.add(o);            }        }    }    public void deleteObserver(Observer o) {        if(personList.contains(o)){            personList.remove(o);        }            }    public void notifyObservers() {        for (int i = 0; i < personList.size(); i++) {            Observer o = personList.get(i);            o.update(this);        }    }    public void doForeCast(String t,String mess,int max,int min){        forecastTime = t;        forcastMess = mess;        minTemperature = min;        maxPemperature = max;        notifyObservers();    }    public String getForecastTime() {        return forecastTime;    }    public String getForcastMess() {        return forcastMess;    }    public int getMaxPemperature() {        return maxPemperature;    }    public int getMinTemperature() {        return minTemperature;    }        }

Specific observer

Package COM. observer2; public class person implements observer {subject subjectone, subjecttwo; // The topic string forecasttime, forecasponess; string tourstarttime, tourmess; int maxtemperature, mintemperature; Public Person (subject one, subject Two) {This. subjectone = one; this. subjecttwo = two; subjectone. addobserver (this); subjecttwo. addobserver (this);} public void Update (subject) {If (subject instanceof weaherstation) {weaherstation Ws = (weaherstation) subject; forecasttime = ws. getforecasttime (); forecasponess = ws. getforcasponess (); maxtemperature = ws. getmaxpemperature (); mintemperature = ws. getmintemperature (); system. out. print ("prediction Date:" + forecasttime + ","); system. out. print ("weather condition:" + forecasponess + ","); system. out. print ("maximum temperature:" + maxtemperature + ","); system. out. println ("minimum temperature:" + mintemperature + ". ");} else if (subject instanceof travelagency) {travelagency TA = (travelagency) subject; tourstarttime = TA. gettourstarttime (); tourmess = TA. gettourmess (); system. out. print ("Tourism start date:" + tourstarttime + ","); system. out. println ("tourism information:" + tourmess + ". ");}}}

Write a test program

Package COM. observer2; public class application {public static void main (string [] ARGs) {weaherstation = new weaherstation (); // The subject travelagency = new travelagency (); // subject: person boy = new person (weaherstation, travelagency); weaherstation. doforecast ("10", "overcast with light rain", 28, 20); travelagency. givemess ("10", "Huangshan 2 day tour"); weaherstation. doforecast ("11", "Clear to cloudy", 30, 21); travelagency. givemess ("11", "Lijiang 1 day tour ");}}

The running result is as follows:

Forecast Date: 10 days, weather condition: overcast with light rain, maximum temperature: 28, minimum temperature: 20.
Tourism Start Date: 10, tourism information: Huangshan 2 day tour.
Forecast Date: 11, weather condition: Clear to cloudy, maximum temperature: 30, minimum temperature: 21.
Tourism Start Date: 11, tourism information: Lijiang 1 day tour.

Suitable for the observer mode: 1. When the data of an object is updated, other objects need to be notified, but this object does not need to be tightly coupled with those objects to be notified. 2. When the data of an object is updated, this object requires other objects to update their own data, but this object does not know how many objects need to update data.
 

 

 

 

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.