My understanding of the observer pattern

first look at a scene

There is a process type of business in many businesses. For example, the ordering operation of an online shopping mall system may include the following processes:

  1. check stock
  2. deduction of inventory
  3. Generate orders
  4. notify user
  5. Notify merchant

simple implementation

The most direct and simple method is to call APIs such as inventory check, inventory notch, order generation, user notification, merchant notification, etc. in the operation of placing an order according to the needs of the current business. Then get it done.

existing problems

The problem with this method is that if we need to add a new operation in a certain process,
for example, after deduction of inventory, we need to add an operation, which is to write the result of inventory deduction into a log file.
Then we need to modify the operation of placing an order and add this operation to the operation of placing an order.
This will make the operation of placing an order more and more complicated, which is not conducive to maintenance.
Such code will become difficult to maintain and not conducive to expansion. How to decouple these processes and the operation of placing an order, so as to better embrace changes? Observer mode can solve such a problem.

solution

We can use the Observer pattern to solve this problem. The observer pattern is defined as follows:
Observer pattern (Observer Pattern): It can also be called the subscription-publish pattern, which defines a one-to-many dependency relationship between objects. When the state of an object changes, all the objects that depend on it objects are notified and updated automatically.
In the above scenario, we can use the order placing operation as a subject, and operations such as inventory check, inventory deduction, order generation, user notification, and merchant notification as observers. When an order operation occurs, all observers will be notified and perform their own operations.
In this way, when the process needs to be added or removed, there is no need to modify the order placing operation, only the list of observers needs to be added or removed. Changes in requirements can be easily resolved.

Observer pattern class diagram representation

observes
1
*
notifies
1
*
Subject
+attach(observer:Observer)
+detach(observer:Observer)
+notify()
ConcreteSubject
+state:string
+getState()
+setState(state:string)
Observer
+update(subject:Subject)
ConcreteObserver
+observerState:string
+update(subject:Subject)

simple understanding

  1. The observer inherits the observer interface and implements the update method.
  2. The observed object inherits the observed object interface and implements the attach, detach, and notify methods.
  3. The observed object holds a list of observers, and when the observed object changes, all observers will be notified.
  4. 被观察者的变化会触发观察者的update方法,观察者可以根据自己的需求来实现update方法。

代码实现

观察者接口

//观察者接口
public interface Observer {
    
    
    void update(Subject subject);
}
//被观察者接口
public interface Subject {
    
    
    void attach(Observer observer);

    void detach(Observer observer);

    void notifyObservers();
}

public class OrderService implements Subject {
    
    
    private List<Observer> observers = new ArrayList<>();

    public void attach(Observer observer) {
    
    
        observers.add(observer);
    }

    public void detach(Observer observer) {
    
    
        observers.remove(observer);
    }

    public void notifyObservers() {
    
    
        for (Observer observer : observers) {
    
    
            observer.update(this);
        }
    }

    public void createOrder() {
    
    
        System.out.println("创建订单");
        notifyObservers();
    }
}

public class ObserverOne implements Observer {
    
    
    public void update(Subject subject) {
    
    
        System.out.println("观察者收到通知,执行自己的操作");
    }
}
public class ObserverTest {
    
    
    public static void main(String[] args) {
    
    
        OrderService orderService = new OrderService();
        ObserverOne observerOne = new ObserverOne();
        orderService.attach(observerOne);
        orderService.createOrder();
    }
}

优缺点

优点

  1. 观察者和被观察者之间是抽象耦合的。
  2. 建立一套触发机制。
  3. 观察者模式支持广播通信。
  4. 观察者模式符合“开闭原则”。

缺点

  1. 如果一个被观察者有很多直接和间接的观察者时,将所有的观察者都通知到会花费很多时间。
  2. 如果在观察者和被观察者之间有循环依赖,观察者会等待被观察者处理完再处理,将导致系统崩溃。
  3. 观察者之间有过多的细节依赖,提高时间消耗及程序复杂度。

应用场景

  1. 关联行为场景。需要注意的是,关联行为是可拆分的,而不是“组合”关系。
  2. 事件多级触发场景。
  3. 跨系统的消息交换场景,如消息队列的处理机制。

Guess you like

Origin blog.csdn.net/aofengdaxia/article/details/128787083