The Secret of Patterns - Observer Pattern (1)

Learn the general code of the observer pattern:

1. Definition of target object

2, the specific target object definition.

3. Let's take a look at the interface definition of the observer

4. Look at the specific implementation of the observer.

 Let's start with a general observer pattern example:

1: Define a target object: Add, delete, and most importantly notify the observer method of the observer (the observer object calls its own method, and the method parameter is the target object)

package com.ObserverPatternCommon;

import java.util.ArrayList;
import java.util.List;

/*
 * The target object, which knows the observers that observe it, and raises the interface for registering (adding) and removing observers
 * */ 
public  class Subject {
     // Save the registered observer object 
    private List<Observer> observers= new ArrayList<Observer> ();
    
    // attach detach notifyObserver
     // Add the observer to the collection 
    public  void attach(Observer observer)
    {
        observers.add(observer);
    }
    // Delete the specified observer in the collection 
    public  void detach(Observer observer)
    {
        observers.remove(observer);
    }
    
    // Notify all registered observer objects 
    protected  void notifyObservers()
    {
        for(Observer observer:observers)
        {
            observer.update(this);
        }
    }

}

2. Establish a specific target object: inherit the target object, and add the methods required by the specific target object: the setting and acquisition of the state of a target object, and notify the observer when the state is set.

package com.ObserverPatternCommon;

/*
 * The specific target object is responsible for storing the relevant state into the corresponding observer object
 * */
public class ConcreteSubject extends Subject {

    // Save the state of the target object 
    private String subjectState;

    public String getSubjectState() {
        return subjectState;
    }

    public  void setSubjectState(String subjectState) {
         this .subjectState = subjectState;
         this .notifyObservers(); // When the state changes, notify all observers 
    }
}

3. Create an observer interface:

package com.ObserverPatternCommon;

/*
 * This is an observer interface that defines an update interface for objects that are notified when the target changes
 * */
public interface Observer {

    // Updated interface, subject represents the incoming target object, which is convenient to obtain the corresponding target object status 
    public  void update(Subject subject);
    
}

4. Establish a specific observer interface: because when the observer is notified by the target object, the observer needs to call its own method, update here.

package com.ObserverPatternCommon;

/*
 * A specific observer object that implements an updated method to keep the state of itself and the target consistent
 * */
public class ConcreteObserver implements Observer {

    // The state of the observer 
    private String observerState;
    
    /*
     * Get the state of the target class and synchronize it to the state of the observer
     * */
    @Override
    public void update(Subject subject) {
        observerState=((ConcreteSubject)subject).getSubjectState();
    }

}

The above is the general structure of the observer pattern.

 

Let's take a specific example: when the weather changes, all registered observer users (such as girlfriend and mother here) need to be notified.

The first step: establish the weather target object class: including user registration method, user logout method, user notification method

package WeatherObserverPattern;

import java.util.ArrayList;
import java.util.List;

/*
 * The target object, which knows the observers that observe it, and raises the interface for registering (adding) and removing observers
 * */ 
public  class WeatherSubject {
     // Save the registered observer object 
    private List<Observer> observers= new ArrayList<Observer> ();
    
    // attach detach notifyObserver
     // Add the weather subscriber to the subscriber list 
    public  void attach(Observer observer)
    {
        observers.add(observer);
    }
    // Delete the specified weather subscription person in the collection 
    public  void detach(Observer observer)
    {
        observers.remove(observer);
    }
    
    // Notify everyone who has subscribed to the weather 
    protected  void notifyObservers()
    {
        for(Observer observer:observers)
        {
            observer.update(this);
        }
    }

}

Step 2: Establish a specific weather target object class: include the weather information method, and call the notification user method when the weather information is changed.

package WeatherObserverPattern;

/*
 * The specific target object is responsible for storing the relevant state into the corresponding observer object
 * */
public class ConcreteWeatherSubject extends WeatherSubject {

    // Get the content information of the weather 
    private String weatherContent;
    
    public String getWeatherContent() {
        return weatherContent;
    }

    public  void setWeatherContent(String weatherContent) {
         this .weatherContent = weatherContent;
         // The content is available, indicating that the weather has been updated, notify all subscribed people 
        this .notifyObservers();
    }
}

Step 3: Define the user observer interface: include an update interface

package WeatherObserverPattern;

/*
 * This is an observer interface that defines an update interface for objects that are notified when the target changes
 * */
public interface Observer {

    // Updated interface, subject represents the incoming target object, which is convenient to obtain the corresponding target object status 
    public  void update(WeatherSubject subject);
    
}

Step 4: Define the specific class of user observer: Contains variables: user name, reminder information for different users, and variables used to receive weather information. When the weather class notifies the user, the user will call the update method and pass in

Weather class object, get weather information through the weather class object.

package WeatherObserverPattern;

/*
 * A specific observer object that implements an updated method to keep the state of itself and the target consistent
 * */
public class ConcreteObserver implements Observer {
    
    // The name of the observer, who received this message, Huang Ming's girlfriend, his mother 
    private String observerName;
     // The content of the weather, this message is obtained from the target 
    private String weatherContent;
     // The content of the reminder, Huang Ming's girlfriend reminds the date, while his mother reminds shopping 
    private   String remindThing;
    
    public String getObserverName() {
        return observerName;
    }
    public void setObserverName(String observerName) {
        this.observerName = observerName;
    }
    public String getWeatherContent() {
        return weatherContent;
    }
    public void setWeatherContent(String weatherContent) {
        this.weatherContent = weatherContent;
    }
    public String getRemindThing() {
        return remindThing;
    }
    public void setRemindThing(String remindThing) {
        this.remindThing = remindThing;
    }    
    /*
     * Get the state of the target class and synchronize it to the state of the observer
     * */
    @Override
    public void update(WeatherSubject subject) {
        weatherContent=((ConcreteWeatherSubject)subject).getWeatherContent();
        System.out.println(observerName+"收到了:"+weatherContent+","+remindThing);
    }

}

Finally: implement the call to notify the user of the weather information.

package WeatherObserverPattern;

public  class Customer {

    public static void main(String[] args) {

        // 1, create the target 
        ConcreteWeatherSubject weather= new ConcreteWeatherSubject();
         // 2, create the observer 
        ConcreteObserver observerGirl= new ConcreteObserver();
        observerGirl.setObserverName( "Huang Ming's girlfriend" );
        observerGirl.setRemindThing( "It's our first date, in the center of the street" );
        
        ConcreteObserver observerMum=new ConcreteObserver();
        observerMum.setObserverName( "Mom" );
        observerMum.setRemindThing( "It's a good day for shopping, go to Tianhong to shop tomorrow" );
        
        // 3, register the observer 
        weather.attach(observerGirl);
        weather.attach(observerMum);
        // 4. The target publishes the weather 
        weather.setWeatherContent("Tomorrow will be sunny, blue sky and white clouds, and the temperature will be 28 degrees" );
    }

}

Results of the:

Huang Ming's girlfriend received it: tomorrow the weather will be sunny, blue sky and white clouds, the temperature is 28 degrees, it is our first date, the location is Jiexin Park
Mom received it: tomorrow the weather will be sunny, blue sky and white clouds, and the temperature will be 28 degrees. It is a good day for shopping. Tomorrow, I will go to Tianhong to scan the goods.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324863939&siteId=291194637