Novice code farmer talking about observer pattern (Java language simple implementation)

Source: Internet
Author: User

One: What is the Observer pattern:

Official definition: Defines a one-to-many dependency between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated.

For example, many people will subscribe to the weather forecast, and when the weather station gets tomorrow ( target object ), it will notify the person who subscribed to the weather forecast (the observer ), then the subscribers will be based on the weather conditions tomorrow to do the corresponding treatment (stay at home?). Going out for an outing? Go shopping ... )

Two: Two characters of the Observer pattern:

The first role: the target object (subject), the object of interest to the observer, and its change causes changes in the observer, such as the weather conditions mentioned above.

Second role: Observer (Observer), one or more, focusing on the state of the target object, such as the people who subscribed to the weather forecast in the example above.

Three: The Observer pattern three common role scenarios:

1. A target object, an observer object, such as as long as you subscribe to the weather forecast alone

2. A target object, multiple observer objects, such as your father, your mother and you have subscribed to the weather forecast

3. Multiple target objects, one observer object, such as a person who subscribes to the weather forecast and subscribes to a newspaper

Four: Push model and pull model (the following code will have comments):

PUSH MODEL: Observer when the update () method is executed, the specific parameters passed to it by the subject are obtained, and the target object actively pushes the target details to the viewer.

Pull model: Observer, when executing the update () method, obtains a subject object that subject passes to it, and observer what parameters it needs to fetch itself.

V: Java code implements the Observer pattern:

First, provide the most basic observer Pattern code framework:

1. Create a new Subject parent class

Importjava.util.ArrayList;Importjava.util.List;/** Target object, he knows to observe its observer, and provide the interface to register (add) and remove the Observer*/ Public classSubject {//object used to save the registered observer    PrivateList<observer> observers =NewArraylist<observer>(); //adding observers to a multi-list object     Public voidAttch (Observer Observer) {observers.add (Observer); }        //deletes the specified observer object from the collection     Public voidDelete (Observer Observer) {observers.remove (Observer); }        //notifies all registered observers of the message    protected voidNotifyobserver () { for(Observer observer:observers) {observer.update ( This); }    } }

2. Create a specific subject implementation class

/** Specific target object, responsible for depositing the relevant status to the corresponding observer object*/ Public classConcreteSubjectextendsSubject {//the status of the target object    PrivateString subjectstate;  PublicString getsubjectstate () {returnsubjectstate; }     Public voidsetsubjectstate (String subjectstate) { This. subjectstate =subjectstate;  This. Notifyobserver (); }    }

3. Create a new observer interface

/**/publicinterface  Observer {        /* * Update interface     * Subject incoming target object for easy access to the target object's     status */     Public void Update (Subject Subject);            }

4. Create a new Observer implementation class

/**/Publicclassimplements  Observer {    private  String observerstate;    @Override    publicvoid  update (Subject Subject) {        //  TODO auto-generated Method Stub        observerstate = ((ConcreteSubject) subject). Getsubjectstate ();    }  }

Here I use a specific example to implement the observer pattern, which gives you a clearer understanding of the observer pattern

One such scene, Little East's girlfriend and mother have subscribed to a small East development of a weather forecast software, when the daily weather is not the same, little East's girlfriend and mother received weather notice, will arrange tomorrow's itinerary. Small east of this software can tease girlfriend and mom happy, the original program Ape also has this role, see below How the program demonstrates:

1. Create a new Weathersubject parent target object

Importjava.util.ArrayList;Importjava.util.List;/** Target object, he knows to observe its observer, and provide the interface to register (add) and remove the Observer*/ Public classWeathersubject {//a person to save a subscription to the weather    PrivateList<observer> observers =NewArraylist<observer>(); //add people who subscribe to the weather to the subscription list     Public voidAttch (Observer Observer) {observers.add (Observer); }        //deletes the specified subscription in the collection for the weather person     Public voidDelete (Observer Observer) {observers.remove (Observer); }        //notify everyone who has subscribed to the weather    protected voidNotifyobserver () { for(Observer observer:observers) {observer.update ( This); }    } }

2. Create a Weathersubject Concrete implementation object (the observer needs to get the state from the target object only the weather content )

/** Specific target object, responsible for depositing the relevant status to the corresponding observer object*/ Public classConcreteweathersubjectextendsWeathersubject {//Get the weather content information    PrivateString weathercontent;  PublicString getweathercontent () {returnweathercontent; }     Public voidsetweathercontent (String weathercontent) { This. weathercontent =weathercontent; //The content has, the weather is updated, notify all the people who subscribe         This. Notifyobserver (); }}

3. Create a new observer interface

/**/publicinterface  Observer {        /* * Update interface     * Subject incoming target object for easy access to the target object's     status */     Public void Update (weathersubject subject);            }

4. Create a specific Weathersubject object

/** Specific observer objects, implementing updated methods to align their state and target State*/ Public classConcreteobserverImplementsObserver {//The Observer's name, who received the message, the little east girlfriend or his mother    PrivateString Observername; //weather content, this message is obtained from the target    PrivateString weathercontent; //reminded of the content of little Dong's girlfriend reminds of dating while his mom reminds shopping    PrivateString remindthing;  PublicString Getobservername () {returnObservername; }     Public voidsetobservername (String observername) { This. Observername =Observername; }     PublicString getweathercontent () {returnweathercontent; }     Public voidsetweathercontent (String weathercontent) { This. weathercontent =weathercontent; }     PublicString getremindthing () {returnremindthing; }     Public voidsetremindthing (String remindthing) { This. remindthing =remindthing; }         Public voidUpdate (weathersubject subject) {weathercontent=((concreteweathersubject) subject). Getweathercontent (); System.out.println (Observername+ "received" + Weathercontent + "," +remindthing); }  }

5. Test class

 Public classClient { Public Static voidMain (string[] args) {//1. Create a targetConcreteweathersubject Weathersubject =NewConcreteweathersubject (); //2. Create the viewerConcreteobserver Observergirl =NewConcreteobserver (); Observergirl.setobservername ("Little Dong's Girlfriend"); Observergirl.setremindthing ("It's our first date, the place Huaroli square, no amount."); Concreteobserver Observermom=NewConcreteobserver (); Observermom.setobservername ("Little Dong's mother"); Observermom.setremindthing ("It's a good day for shopping.); //3. Registered ObserverWeathersubject.attch (Observergirl);           Weathersubject.attch (OBSERVERMOM); //4. Target release WeatherWeathersubject.setweathercontent ("Tomorrow sunny, clear skies, temperature 28 ℃"); }}

6. Running Results

All Programs ape Dick Silk, the original observer mode can also come to the girls, you are waiting for what, now the Observer mode has a basic understanding of it. Finally, let's talk about what we can do with the Observer pattern:

    • The observer pattern can be used when an abstract model has two facets, one of which is dependent on the other and the state changes on the other.
    • If you change a state, you need a colleague to change other objects, and you do not know how many objects need to be changed, you can choose the Observer mode.
    • When an object must notify other objects, but you want this object to be loosely coupled with other objects that it notifies, you can also use the Observer pattern.

Thank you crossing, we will see you next time!

Novice code farmer talking about observer pattern (Java language simple implementation)

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.