Design pattern - observer pattern

Related links:

[design mode] column: [design mode] column

Relevant examples can be downloaded: Examples of common Java design patterns

Observer mode

Observer Pattern refers to one to many dependencies among multiple objects. When the state of an object changes, all objects that depend on it are notified and automatically updated. This pattern is sometimes called publish subscribe mode and model view mode. It is an object behavior mode.

When an object is modified, the objects that depend on it are automatically notified.

advantage

  • It reduces the coupling relationship between the target and the observer, which is an abstract coupling relationship, which conforms to the principle of dependency inversion

  • A trigger mechanism is established between the target and the observer

shortcoming

  • The dependency between the target and the observer is not completely removed, and circular references may occur

  • When there are many observers, the announcement takes a lot of time, which affects the efficiency of the program

Role of observer mode

When implementing the observer mode, it should be noted that the specific target object and the specific observer object cannot be called directly, otherwise they will be closely coupled, which violates the object-oriented design principle.

The main roles of the observer model are as follows:

Abstract Subject role

Also called abstract target class, it provides an aggregation class for saving observer objects, methods for adding and deleting observer objects, and abstract methods for notifying all observers.

Concrete Subject role

Also known as the concrete target class, it implements the notification method in the abstract target to notify all registered observer objects when the interior of the concrete subject changes.

Abstract Observer role

It is an abstract class or interface that contains an abstract method that updates itself and is called when notified of changes to a specific topic.

Concrete Observer role

Implement the abstract method defined in the abstract observer to update its own state when notified of changes to the target.

Sample code

Abstract observer

/**
 * Observer pattern - Abstract observer
 *
 */
public interface Observer {

    /**
     * Operations performed by the observer after being notified
     */
    public void someThingToDo(String weatherType);

}

Specific observer

/**
 * Observer mode - specific observer
 *
 * ((TV)
 *
 */
public class TVObserver implements Observer{
    @Override
    public void someThingToDo(String weatherType) {
        System.out.println("According to the TV weather forecast, the current weather is:"+weatherType);
    }
}
/**
 * Observer mode - specific observer
 *
 * (Sina)
 */
public class SinaObserver implements Observer{
    @Override
    public void someThingToDo(String weatherType) {
        System.out.println("According to Sina weather forecast, the current weather is:"+weatherType);
    }
}

Abstract topic (Abstract target)

/**
 * Observer pattern - abstract topic (abstract goal)
 *
 */
public interface Subject {

    /**
     * Add observer
     * @param observer
     */
    public void addObserver(Observer observer);

    /**
     * Remove observer
     * @param observer
     */
    public void removeObserver(Observer observer);

    /**
     * Notify all observers
     */
    public void notifyObservers();

}

Specific themes (specific objectives)

/**
 * Observer model - specific topics (specific objectives)
 *
 * (Take weather forecast as an example. This class means: weather)
 *
 */
public class WeatherSubject implements Subject{

    // Define a collection of observers
    private List<Observer> observers = new ArrayList<>();
    // Weather type
    private String weatherType;

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        observers.forEach(observer -> {
            observer.someThingToDo(weatherType);
        });
    }

    /**
     * Set weather type
     * @param weatherType   Weather type
     */
    public void setWeatherType(String weatherType) {
        this.weatherType = weatherType;
        // Inform the observers that the weather has changed
        notifyObservers();
    }
}

Test class

/**
 * Observer mode
 *
 */
public class ObserverPatternDemo {

    public static void main(String[] args) {
        // Build a weather forecast
        WeatherSubject weatherSubject = new WeatherSubject();
        // Add observer
        weatherSubject.addObserver(new TVObserver());
        weatherSubject.addObserver(new SinaObserver());
        // Set weather forecast
        weatherSubject.setWeatherType("cloudy");
        System.out.println("---------------------");
        weatherSubject.setWeatherType("The sun shines brightly");
    }

}

 

Conclusion

1. See more about design patterns [design mode] column

2. Relevant example codes can be downloaded: Examples of common Java design patterns

PS:   [ Examples of common Java design patterns Included in] [design mode] column The code involved in the code can be downloaded by students who need the code. If you have downloaded it before, you don't need to download it again~

If the above contents are incorrect or need to be supplemented, please consult more and update and correct them in time~

Welcome to comment ~ thank you for your praise~

Keywords: Java Programming Design Pattern

Added by Nuv on Sat, 25 Dec 2021 20:28:47 +0200