Observer mode

1, Definition

One to many dependencies are defined between objects. In this way, when an object changes state, the objects that depend on it will receive notification and update automatically. Generally speaking, it is the publish and subscribe mode. The publisher publishes information, the subscriber obtains information, and can receive information after subscribing, but can't receive information without subscribing.

2, Structure diagram


The figure reflects the four roles of the observer pattern

  • **Abstract observer role: * * that is, an abstract topic. It saves all references to observer objects in a collection. Each topic can have any number of observers. Abstract topics provide an interface to add and remove observer roles. It is generally implemented with an abstract class and interface.
  • **Abstract observer role: * * define an interface for all concrete observers and update themselves when notified by the topic.
  • **Specific observer role: * * that is, a specific topic. When the internal state of the collective topic changes, all registered observers will send a notice.
  • **Specific observer role: * * implement the update interface required by the abstract observer role, while coordinating its own state with the drawing state.

3, Take a chestnut

There is a WeChat official account service. It releases messages from time to time. It can receive the push message when it concerns the official account.

1. Define an abstract observer interface

package com.jstao.observer;

/***
 * Abstract observer interface
 * Declare the methods of adding, deleting and notifying observers
 * @author jstao
 *
 */
public interface Observerable {
    
    public void registerObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObserver();
    
}

2. Define an abstract observer interface

package com.jstao.observer;

/***
 * Abstract observer
 * An update() method is defined. When the observer calls the notifyObservers() method, the observer's update() method will be called back.
 * @author jstao
 *
 */
public interface Observer {
    public void update(String message);
}

3. Define the observed, implement the observeable interface, and specifically implement the three methods of the observeable interface. At the same time, there is a List set to save the registered observers. When the observer needs to be notified, traverse the set.

package com.jstao.observer;

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

/**
 * The official account is WeChat public service.
 * The Observerable interface is implemented, and the three methods of Observerable interface are implemented in detail
 * @author jstao
 *
 */
public class WechatServer implements Observerable {
    
    //Note that the generic parameter of the List set is the Observer interface. The design principle is interface oriented programming rather than implementation oriented programming
    private List<Observer> list;
    private String message;
    
    public WechatServer() {
        list = new ArrayList<Observer>();
    }
    
    @Override
    public void registerObserver(Observer o) {
        
        list.add(o);
    }
    
    @Override
    public void removeObserver(Observer o) {
        if(!list.isEmpty())
            list.remove(o);
    }

    //ergodic
    @Override
    public void notifyObserver() {
        for(int i = 0; i < list.size(); i++) {
            Observer oserver = list.get(i);
            oserver.update(message);
        }
    }
    
    public void setInfomation(String s) {
        this.message = s;
        System.out.println("Wechat service update message: " + s);
        //Message update, notify all observers
        notifyObserver();
    }

}

4. Define the specific observers. The specific observer of WeChat official account is User

package com.jstao.observer;

/**
 * Observer
 * The update method is implemented
 * @author jstao
 *
 */
public class User implements Observer {

    private String name;
    private String message;
    
    public User(String name) {
        this.name = name;
    }
    
    @Override
    public void update(String message) {
        this.message = message;
        read();
    }
    
    public void read() {
        System.out.println(name + " Push message received: " + message);
    }
    
}

5. Write a test class

First, three users were registered, ZhangSan,LiSi,WangWu. The official account issued a message."PHP It is the best language in the world!",All three users received the message.

user ZhangSan After seeing the news, it was quite shocked and decisive to cancel the subscription. At that time, the official account pushed another message. ZhangSan No message received, other users

Push messages can still be received normally
```java
package com.jstao.observer;

public class Test {
    
    public static void main(String[] args) {
        WechatServer server = new WechatServer();
        
        Observer userZhang = new User("ZhangSan");
        Observer userLi = new User("LiSi");
        Observer userWang = new User("WangWu");
        
        server.registerObserver(userZhang);
        server.registerObserver(userLi);
        server.registerObserver(userWang);
        server.setInfomation("PHP It is the best language in the world!");
        
        System.out.println("----------------------------------------------");
        server.removeObserver(userZhang);
        server.setInfomation("JAVA It is the best language in the world!");
        
    }
}

4, Actual combat cases

spring's event driven model: https://www.cnblogs.com/fingerboy/p/6393644.html
netty also has its shadow

Keywords: Design Pattern

Added by dynodins on Tue, 28 Dec 2021 19:23:01 +0200