Observer mode belongs to behavior design mode, also called publish and subscribe mode, which is widely used in practical scenarios, such as email subscription, wechat public account subscription, etc

Observer pattern template

Need two roles in the observer pattern, is the observer and the observed respectively, two of them as there are also many, such as producers and consumers, the publisher and subscribers, the publisher and the listener, but the essence is the same A specific code of the observer pattern is given below by the observer interface and defines a series of operating the observer method, and the realization of his class

// Observed interface
public interface Observable{
	void registerObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObserver(Message message);
}

// The observed implementation class
public class ObservableImpl implements Observable{
	private List<Observer> list = new ArrayList<>();
    
    void registerObserver(Observer observer){
    	list.add(observer);
    }
    
    void removeObserver(Observer observer){
    	list.remove(observer);
    }
    
    void notifyObservers(String message){
    	list.foreach(item -> item.doSomeThing(message));
    }
    
    void doThings(a){
    	System.out.println("The observed did something.");
        this.notifyObservers(); }}Copy the code

Observer interface, and implementation classes

// Observer interface
public interface Observer{
    void handle(String message);
}


// Observer 1
public class Observer1 implements Observer{
	void handle(String message){
        // Observer 1's logicSystem.out.println(message); }}// Observer 2
public class Observer2 implements Observer{
	void handle(String message){
        // Observer 2's logicSystem.out.println(message); }}Copy the code

The final test

/ / test
public class Demo{
	public static void main(String[] args){
        // Create a subscriber
    	Observer observer1 = new Observer1();
        Observer observer2 = new Observer2();
        
        // Register subscribers
        Observable observable = new ObservableImpl();
        observable.registerObserver(observer1);
        observable.registerObserver(observer2);
        
        // Issue a notification
        observable.notifyObservers(newMessage); }}Copy the code

















The JDK comes with an observer mode interface

Careful people should be able to find the observed responsibility is not a single, it is to deal with their own logic, and logic, register, delete, notify the observer should a parent class abstracts, deal only with the responsibility of the observed, and the observed only concerned with their own logic, fortunately, the JDK have ready-made observed in the parent class, Observable, and also provides the interface Observer. Next, use the parent class and interface provided by JDK to implement the Observer mode. You must be familiar with spies. The next simulated scenario is based on this. During the warring states period, everything is done and rees in different countries, different position, Reese want to extinguish the republic of Korea, so everything is done to side had planted a spy, everything is done to do, can timely find spy, report to Reese, doing but rees knew that everything is done, will report to the emperor qin shi huang, there, everything is done is the observer, Li Si, however, is the observer who first created this interface, because Han Feizi is also a human, and he also wants to eat, drink and defecate like ordinary people

/ / interface
public interface Person {
    void eat(a);

    void play(a);
}
Copy the code

To create hanfeizi as an Observable, implement the Observable interface provided by the JDK

public class HanFeiZi extends Observable implements Person {

    @Override
    public void eat(a) {
        System.out.println("Han Feizi: It's time to eat.");
        super.setChanged();
        super.notifyObservers("Han Feizi is eating.");
    }

    @Override
    public void play(a) {
        System.out.println("Han Feizi: Started playing games.");
        super.setChanged();
        super.notifyObservers("Han Feizi is playing a video game."); }}Copy the code

Then it is the implementation of lisi Observer, Observer implementation is the Observer interface, he inside the definition of an update method, the spy sent to the message processing

public class LiSi implements Observer {

    @Override
    public void update(Observable o, Object arg) {
        System.out.println(Li Si: I observed Han Feizi's activity and began to report it to my boss...);
        System.out.println("Li Si: report to Boss Qin," + arg);
        System.out.println("Reese: This is the end."); }}Copy the code

There’s one more parameter that the Observable interface doesn’t use in the Update method. It’s actually the HanFeiZi object, which is the only Observable that you can use to add or delete an observer. There must be more than one person who wants to destroy Han Feizi, and this is not a realization of the final test

public class Main {
    public static void main(String[] args) {
        HanFeiZi hanFeiZi = new HanFeiZi();
        LiSi liSi = newLiSi(); hanFeiZi.addObserver(liSi); hanFeiZi.eat(); hanFeiZi.play(); }}Copy the code

The results of

Li Si: I observed Han Feizi's activities and began to report to the boss... Li Si: Report to Boss Qin, Han Feizi is having dinner Li Si: Report finished Han Feizi: Started to play games Li Si: Observed Han Feizi's activities, began to report to the boss... Li Si: Report to Boss Qin, Han Feizi is playing games li Si: Report finishedCopy the code














Observer mode considerations

Asynchronous processing problem ** When the observed makes an action, all observers should be notified, and only after one observer finishes processing can another observer be notified. If one observer processes slowly, the operation speed of the whole system will be slowed down. Therefore, the best solution is to handle observer logic asynchronously, and many observer-pattern-like frameworks, such as Kafka, are implemented asynchronously