Chapter 18 Behavioral Pattern—Observer Pattern


Behavioral patterns are used to describe the complex flow control of programs at runtime, that is, to describe how multiple classes or objects cooperate with each other to complete tasks that a single object cannot complete alone. It involves the allocation of responsibilities between algorithms and objects. Behavioral patterns are divided into class behavior patterns and object behavior patterns:

  • Class behavior pattern: using inheritance mechanism to dispatch behavior between classes

  • Object behavior pattern: Use composition or aggregation to distribute behavior among objects

Since the combination relationship or aggregation relationship is less coupled than the inheritance relationship and satisfies the "principle of composite reuse", the object behavior pattern has greater flexibility than the class behavior pattern.

Behavioral patterns are divided into:

  • template method pattern
  • strategy pattern
  • command mode
  • chain of responsibility model
  • state mode
  • Observer pattern
  • intermediary pattern
  • iterator pattern
  • visitor mode
  • Memo mode
  • interpreter mode

The above 11 behavioral patterns, except for the template method pattern and the interpreter pattern, which are quasi-behavioral patterns, the others all belong to the object behavioral pattern.

Observer pattern

Observer pattern : Also known as the Publish/Subscribe (Publish/Subscribe) pattern, it defines a one-to-many dependency relationship 让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己.

solved problem

image-20230524155714641

Zhang San is a boss. Due to poor performance, he borrowed money from Wang Wu, Zhao Liu, and Lao Ba. However, due to poor management, the company collapsed. The creditor must want Zhang San to pay back the money. The creditor trusts Zhang San. Character, I know Zhang San will definitely pay back the money, but I don’t know when.

  • The first way is that the creditors take the initiative to ask Zhang San every day if he has the money to repay. In this way, Zhang has to answer so many inquiries from creditors every day. The creditors are also very busy and need to ask Zhang San every day.
  • The second way is that the creditors take the contract that Zhang San owes money. When Zhang San has money, he takes the initiative to tell the creditors to pay back the money.
  • This one-to-many relationship between Zhang San and his creditors

structure

  • Subject: Abstract subject (abstract observer). The abstract subject role stores all observer objects in a collection. Each subject can have any number of observers. The abstract subject provides an interface to add and delete observer objects. .
  • ConcreteSubject: Specific subject (specific observer), this role stores the relevant status in the specific observer object, and sends notifications to all registered observers when the internal status of the specific subject changes.
  • Observer: Abstract observer is an abstract class of observer. It defines an update interface so that it can update itself when notified of topic changes.
  • ConcrereObserver: A concrete observer that implements the update interface defined by an abstract observer so that it can update its own status when notified of topic changes.

example

WeChat public account

When using WeChat public accounts, everyone will have this experience. When there is new content update in the public account you follow, it will be pushed to the WeChat client that follows the public account. We use the observer mode to simulate such a scenario. WeChat users are observers, and WeChat public accounts are the observed subjects, that is, subject objects. There are multiple WeChat users who follow the public account of Programmer.

abstract observer

public interface Observer {
    
    
    void update(String message);
}

Specific observer : WeChat user, implemented the updated method

public class WeiXinUser implements Observer{
    
    
    private String name;

    public WeiXinUser(String name) {
    
    
        this.name = name;
    }

    @Override
    public void update(String message) {
    
    
        System.out.println(name+"--"+message);
    }
}

abstract observer

public interface Subject {
    
    
    // 添加订阅者(添加观察者对象)
    void attach(Observer observer);
    // 删除订阅者
    void detach(Observer observer);
    // 通知订阅者更新消息
    void notify(String message);

}

Specific observer : WeChat public account, which stores the WeChat users who subscribe to the public account and implements the methods in the abstract topic

public class SubscriptionSubject implements Subject{
    
    
    //定义一个集合,用来存储多个观察者对象
    private List<Observer> weiXinUserList = new ArrayList<>();
    @Override
    //订阅
    public void attach(Observer observer) {
    
    
        weiXinUserList.add(observer);
    }

    @Override
    //取消订阅
    public void detach(Observer observer) {
    
    
        weiXinUserList.remove(observer);
    }

    @Override
    //公众号发表内容
    public void notify(String message) {
    
    
        for (Observer observer: weiXinUserList) {
    
    
            // 调用观察者对象中的update方法
             observer.update(message);
        }
    }
}

test

public class Client {
    
    
    public static void main(String[] args) {
    
    
        //1创建公众号对象 主题类对象(被观察者)
        SubscriptionSubject subject = new SubscriptionSubject();
        //2订阅公众号
        subject.attach(new WeiXinUser("孙悟空"));
        subject.attach(new WeiXinUser("猪悟能"));
        subject.attach(new WeiXinUser("沙悟净"));
        //3公众号更新,发出消息给订阅者(观察者对象)
        subject.notify("公众号更新啦");
    }
}

Problems

advantage:

  • The coupling relationship between the target and the observer is reduced, and there is an abstract coupling relationship between the two.

  • The observed person sends a notification, and all registered observers will receive the information [a broadcast mechanism can be implemented].

shortcoming:

  • If there are many observers, it will take time for all observers to receive notifications sent by the observed.
  • If the observer has cyclic dependencies, then the notification sent by the observer will cause the observer to be called cyclically, which will cause the system to crash.

scenes to be used

  • There is a one-to-many relationship between objects, and changes in the state of one object will affect other objects.
  • When an abstract model has two aspects, one of which depends on the other.

Implementation provided by JDK - Observable

This class was deprecated in JDK9

In Java, the observer pattern is defined through the java.util.Observable class and the java.util.Observer interface. As long as you implement their subclasses, you can write instances of the observer pattern.

**Observable class: **Abstract target class (observable), which has a Vector collection member variable used to save all observer objects to be notified.

  • void addObserver(Observer o) method: used to add new observer objects to the collection.

  • void notifyObservers(Object arg) method: Call the update method of all observer objects in the collection to notify them of data changes. Usually observers who join the collection later are notified first.

  • void setChange() method: used to set an internal flag of boolean type to indicate that the target object has changed. notifyObservers() will only notify observers when it is true.

**Observer interface: **Abstract observer, which monitors changes in the target object. When the target object changes, the observer is notified and calls the update method to perform corresponding work.

Example

Police catch thief

The police catching the thief can also be implemented using the observer pattern. The police is the observer and the thief is the observed.

Observer object

@Data
public class Thief extends Observable {
    
    
    private String name;
    public Thief(String name) {
    
    
        this.name = name;
    }
    public void steal(){
    
    
        System.out.println("小偷:我偷东西了,有没有人来抓我!!!");
        super.setChanged(); // changed  = true
        // 当它为 true 时,notifyObservers() 才会通知观察者。
        super.notifyObservers();
    }
}

observer object

public class Policemen implements Observer {
    
    
    private String name;

    public Policemen(String name) {
    
    
        this.name = name;
    }

    @Override
    public void update(Observable o, Object arg) {
    
    
        System.out.println("警察:" + ((Thief) o).getName() + ",我已经盯你很久了!!!");
    }
}

test

public class Client {
    
    
    public static void main(String[] args) {
    
    
        //创建小偷对象
        Thief thief = new Thief("小偷");
        //创建警察对象
        Policemen policemen = new Policemen("lsc");
        //让警察盯着小偷
        thief.addObserver(policemen);
        //小偷投东西
        thief.steal();
    }
}
小偷:我偷东西了,有没有人来抓我!!!
警察:小偷,我已经盯你很久了!!!

Guess you like

Origin blog.csdn.net/qq_50985215/article/details/130970277