[Java] A brief introduction to the observer pattern

Pattern definition: defines one-to-many dependency between objects, allowing multiple observer objects to monitor a certain topic object at the same time. When the topic object changes, all its dependencies will be notified and updated. According to this diagram, it is
Observer pattern simple design
simple write a code

package Section1.listener;

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

public class ObserverTest {
    
    
    public static void main(String[] args) {
    
    
        Suject suject = new Suject();
        //把观察者1,2塞到容器里面
        Task1 task1 = new Task1();
        Task2 task2 = new Task2();
        suject.addObserver(task1);
        suject.addObserver(task2);

		//对观察者下达一个 new task 通知
        String msg = "new task";
        suject.notifyObserver(msg);
    }
}

class Suject{
    
    
    //容器
    List<Observer> container = new ArrayList<>();
    //add
    public void addObserver(Observer observer){
    
    
        container.add(observer);
    }
    //remove
    public void removeObservce(Observer observer){
    
    
        container.remove(observer);
    }
    //通知
    public void notifyObserver(Object object){
    
    
        for (Observer item : container) {
    
    
            item.update(object);
        }
    }
}

interface Observer{
    
    
    void update(Object object);
}

//观察者1
class Task1 implements Observer{
    
    
    @Override
    public void update(Object object) {
    
    
        System.out.println("Task1 get " + object);
    }
}

//观察者2
class Task2 implements Observer{
    
    
    @Override
    public void update(Object object) {
    
    
        System.out.println("Task2 get " + object);
    }
}

The advantages of the observer pattern are:

  1. Comply with the opening and closing principle
  2. Connections between objects can be established at runtime

application:

  1. JDK
  2. java.util.Observable
  3. Spring

The following is the application code in Spring

//相当于上面案例的Observer
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
    
    
   //相当于update
   void onApplicationEvent(E var1);

   static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
    
    
       return (event) -> {
    
    
           consumer.accept(event.getPayload());
       };
   }
}

His publisher is ApplicationEventMulticaster

Guess you like

Origin blog.csdn.net/qq_67548292/article/details/131970239