All about Java: "Observer mode" in Design Patterns"

Source: Internet
Author: User

The observer mode describes a one-to-many relationship. "One" is called "topic object/Information publisher" and "multiple" is called "Observer ". The observer mode is interpreted by the title of the observer and the topic object: Multiple observer classes need to "obtain" and "use" all or part of specific data provided by a topic class, when a specific data changes, the observer automatically obtains the updated data and performs a series of operations. The "subscription" behavior that is often mentioned on the Internet can be a metaphor for the observer model. For example, if a person is fond of group buying, he hopes to receive notifications whenever there is new group buying information, so he can subscribe to group buying information on the Group Buying website by registering and leaving an email address. Then, the Group Buying website will save the e-mail address of this person to the notification list in the system, the notification list stores the e-mail addresses of many users who want to obtain the latest group buying information. When the Group Buying Network has new group buying information, the new group purchase information will be sent to each email address in the list, that is, each user who subscribes to the information will receive an email with the same content, when some users do not want to receive similar emails, they can click a link similar to "no longer receive such emails" in the email to unsubscribe, that is, the Group Buying website will delete this person's email information from the notification list. In the "subscription" series of behaviors, the user acts as the observer, and the Group Buying website service provider acts as the topic object.

As mentioned above, the observer class needs to "get" and "use" the topic class to provide all or part of specific data. How should we "get" here? In general, "acquisition" can be divided into two ways: 1. After an observer receives a notification of data changes, he/she reads the data he/she needs in the topic. This method is called pull; 2. When theme data changes, all data is sent to the observer regardless of whether the observer uses the data. This method is called push.

After understanding the principles of the observer mode and the two ways to obtain data, let's look at the code implementation for the "subscription" behavior between the user and the Group Buying Network:

For this implementation, we need a topic object interface, an observer interface, a group network object class that implements the topic object interface, two user classes that implement the observer interface, and a test class.

Code of the topic object interface:

Package COM. rong. l. observer; </P> <p>/** <br/> * created on Dec 13,201 0 <br/> * @ version 1.0 <br/> * @ update modify description <br/> */<br/> Public interface subjecter <br/> {<br/> // parameters of the registerobserver and <br/> // removeobserver methods are implemented. <br // object of the observer interface type <br/> // set the user (observer) register with the latest group buying information notification list <br/> Public void registerobserver (Observer O); <br/> // send the user (observer) delete <br/> Public void removeobserver (Observer O) from the notification list ); <br/> // use this method to notify all observers when new group buying information is available <br/> Public void policyobservers (); <br/>}< br/> 

The Group network object class that implements the topic object interface:

Package COM. rong. l. observer; </P> <p> Import Java. util. arraylist; </P> <p>/** <br/> * created on Dec 13,201 0 <br/> * @ version 1.0 <br/> * @ update modify description <br/> */<br/> public class grouppurchseinfo implements subjecter <br/> {<br/> private arraylist <observer> observers; // used to store the observer added to the notification queue </P> <p> private String title; // group purchase title </P> <p> private string description; // group buying description </P> <p> private int leastnumbertos Tart; // minimum number of group purchases </P> <p> Public grouppurchseinfo () // constructor <br/>{< br/> // create a default empty list for storing Observers <br/> Observers = new arraylist <observer> (); <br/>}</P> <p>/** <br/> * <p> description: [register the observer to the notification list of the topic object] </P> <br/> * @ Param o <br/> * @ Author: rong Lei <br/> * @ update: [Date YYYY-MM-DD] [change person name] [Change description] <br/> */</P> <p> Public void registerobserver (Observer O) <br/> {<br/> observers. add (o); <br/>}</P> <p>/** <br/> * <P> Description: [Delete the observer from the notification list of the topic object] </P> <br/> * @ Param o <br/> * @ Author: rong Lei <br/> * @ update: [Date YYYY-MM-DD] [change person name] [Change description] <br/> */</P> <p> Public void removeobserver (Observer O) <br/>{< br/> int I = observers. indexof (o); <br/> if (I> = 0) <br/> {<br/> observers. remove (I); <br/>}</P> <p>/** <br/> * <p> description: [notify the observer in the notification list of all theme objects] </P> <br/> * @ Author: Rong Lei <br/> * @ update: [date YYYY-MM-DD] [change the person's last name Name] [Change description] <br/> */</P> <p> Public void policyobservers () <br/> {<br/> // cyclic observer list, execute the update method for each observer <br/> for (INT I = 0; I <observers. size (); I ++) <br/>{< br/> observer = (observer) observers. get (I); <br/> // all observers implement the update method of the observer interface. Therefore, <br/> // No matter what type of observer object is, you only need to know that it can execute the update method. <Br/> observer. update (title, leastnumbertostart, description ); <br/>}</P> <p>/** <br/> * <p> discription: [update a group purchase information] </P> <br/> * @ Param title <br/> * @ Param leastnumbertostart <br/> * @ Param description <br/> *@ author: rong Lei <br/> * @ update: [date YYYY-MM-DD] [change person name] [Change description] <br/> */<br/> Public void addnewgrouppurchseinfo (String title, int leastnumbertostart, <br/> string description) <br/>{< br/> This. title = title; <br/> This. leastnumbertostart = leastnumbertostart; <br/> This. description = description; <br/> hasnewinfo (); <br/>}</P> <p>/** <br/> * <p> discription: [call this method when group buying content is updated to notify all observers (execute the update method of the observer)] </P> <br/> * @ Author: rong Lei <br/> * @ update: [date YYYY-MM-DD] [change person name] [Change description] <br/> */</P> <p> private void hasnewinfo () <br/>{< br/> policyobservers (); </P> <p >}< br/>

Observer interface code:

Package COM. rong. l. observer; </P> <p>/** <br/> * created on Dec 13,201 0 <br/> * @ version 1.0 <br/> * @ update modify description <br/> */<br/> Public interface observer <br/> {<br/> // update method <br/> Public void Update (String title, int leastnumbertostart, string description); <br/>}< br/>

User Class 1:

Package COM. rong. l. observer; </P> <p>/** <br/> * created on Dec 13,201 0 <br/> * @ version 1.0 <br/> * @ update modify description <br/> */<br/> Public Class Customer implements observer <br/> {<br/> // stores the topic registered by the current observer, you can use this reference to perform operations such as remove. <Br/> private subjecter currentsubject; </P> <p> // group buying information title <br/> private String title; </P> <p> // group purchase Information Description <br/> private string description; </P> <p> // minimum number of group purchases <br/> private int leastnumbertostart; </P> <p>/** <br/> * <p> discription: [constructor method description] </P> <br/> * @ coustructor method. <br/> */<br/> Public customer (subjecter currentsubject) <br/> {<br/> // when this observer object is created, <br/> // automatically registers the created observer object to the notification list of the topic object. <Br/> This. currentsubject = currentsubject; <br/> currentsubject. registerobserver (this); <br/>}</P> <p>/** <br/> * <p> discription: [Delete the current observer from the notification list of the subject object] </P> <br/> * @ Author: Rong Lei <br/> * @ update: [Date YYYY-MM-DD] [change person name] [Change description] <br/> */<br/> Public void unregisterme () <br/>{< br/> // The currentsubject here references the topic object registered by the observer. <br/> currentsubject. removeobserver (this); <br/>}</P> <p>/** <br/> * <p> discription: [method for implementing the observer interface, operations performed on the current type of observer when the subject object data changes] </P> <br/> * @ Param title <br/> * @ Param leastnumbertostart <br /> * @ Param description <br/> * @ Author: rong Lei <br/> * @ update: [Date YYYY-MM-DD] [change person name] [Change description] <br/> */</P> <p> Public void Update (String title, int leastnumbertostart, string description) <br/>{< br/> This. title = title; <br/> This. description = description; <br/> This. leastnumbertostart = leastnumbertostart; <br/> contentofemail (); <br/>}</P> <p>/** <br/> * <p> discription: [Output group buying information received by the current user] </P> <br/> * @ Author: Rong Lei <br/> * @ update: [Date YYYY-MM-DD] [change person name] [Change description] <br/> */</P> <p> Public void contentofemail () <br/>{< br/> system. out. println ("customerone received message: Today's group buying:" + title + ", minimum number of customers:" <br/> + String. valueof (leastnumbertostart) + ", Group Buying Description:" + description); <br/>}</P> <p >}< br/>

User Type 2:

Package COM. rong. l. observer; </P> <p>/** <br/> * created on Dec 13,201 0 <br/> * @ version 1.0 <br/> * @ update modify description <br/> */<br/> public class anothercustomer implements observer <br/>{</P> <p> private subjecter currentsubject; </P> <p> private String title; </P> <p> private string description; </P> <p> private int leastnumbertostart; </P> <p>/** <br/> * <p> discription: [constructor method description] </P> <br/> * @ coustructor method. <br/> */<br/> Public anothercustomer (subjecter currentsubject) <br/> {<br/> This. currentsubject = currentsubject; <br/> currentsubject. registerobserver (this); <br/>}</P> <p>/** <br/> * <p> discription: [Chinese Description of method functions] </P> <br/> * @ Author: Rong Lei <br/> * @ update: [Date YYYY-MM-DD] [change person name] [Change description] <br/> */<br/> Public void unregisterme () <br/> {<br/> currentsubject. removeobserver (this); <br/>}</P> <p>/** <br/> * <p> discription: [description of method functions in Chinese] </P> <br/> * @ Param title <br/> * @ Param leastnumbertostart <br/> * @ Param description <br/> *@ author: rong Lei <br/> * @ update: [Date YYYY-MM-DD] [change person name] [Change description] <br/> */</P> <p> Public void Update (String title, int leastnumbertostart, string description) <br/>{< br/> This. title = title; <br/> This. description = description; <br/> This. leastnumbertostart = leastnumbertostart; <br/> contentofemail (); <br/>}</P> <p>/** <br/> * <p> discription: [Chinese Description of method functions] </P> <br/> * @ Author: Rong Lei <br/> * @ update: [Date YYYY-MM-DD] [change person name] [Change description] <br/> */</P> <p> Public void contentofemail () <br/>{< br/> system. out. println ("customertwo received message: Today's group buying:" + title + ", minimum number of customers:" <br/> + String. valueof (leastnumbertostart) + ", Group Buying Description:" + description); <br/>}</P> <p >}< br/>

Test class:

 Package COM. rong. l. observer; </P> <p>/** <br/> * created on Dec 14,201 0 <br/> * @ version 1.0 <br/> * @ update modify description <br/> */<br/> public class testmain <br/> {</P> <p>/** <br/> * <p> description: [Chinese Description of method functions] </P> <br/> * @ Param ARGs <br/> * @ Author: Rong Lei <br/> * @ update: [Date YYYY-MM-DD] [change person name] [Change description] <br/> */</P> <p> Public static void main (string [] ARGs) <br/>{< br/> grouppurchseinfo = ne W grouppurchseinfo (); // create a topic object <br/> customer customerone = new customer (grouppurchseinfo ); // create an observer <br/> // create another observer <br/> anothercustomer customeranotherone = new anothercustomer (grouppurchseinfo ); </P> <p> // update the group buying information of the topic object. The first and second rows are output. <br/> grouppurchseinfo. addnewgrouppurchseinfo ("group buying KTV", 8, "4-hour discount, including buffet! "); <Br/> // remove observer 1 from the notification list of the topic object <br/> customerone. unregisterme (); <br/> // update the group buying information of the topic object, and output the third line <br/> grouppurchseinfo. addnewgrouppurchseinfo ("group ktv2", 8, "4-hour discount, including buffet! "); <Br/> // remove observer 2 from the notification list of the topic object <br/> customeranotherone. unregisterme (); <br/> // update the group buying information of the topic object. This time, all the two observers are removed from the notification list of the topic object, so no output is displayed. <br/> grouppurchseinfo. addnewgrouppurchseinfo ("group ktv3", 8, "4-hour discount, including buffet! "); <Br/>}< br/>

 

Output:

Customerone received the message: Today's group buying: Group Buying KTV, minimum number of group buying: 8, Group Buying Description: 4-hour discount, including buffet!
Customertwo received the message: Today's group buying: Group Buying KTV, minimum number of group buying: 8, Group Buying Description: 4-hour discount, including buffet!
Customertwo received the message: Today's group buying: Group Buying ktv2, minimum number of group buying: 8, Group Buying Description: 4-hour discount, including buffet!

The above Code describes how to use push to get data from the observer. The update method of the observer has three fixed parameters, which are obtained by each observer.

What is the pull method? The pull method is to pass in the reference of the topic object as a parameter whenever the corresponding observer update () method is executed when the topic object calls the yyobservers () method, in this way, the observer's update (subjecter s) method can use S. get.

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.