模式定义:定义了对象之间的一对多依赖,让多个观察者对象同时监听某一个主题对象,当主题对象发生变化时,他的所有依赖者都会收到通知并且更新
依照这个图,简单的写一个代码
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<>();//addpublic void addObserver(Observer observer){container.add(observer);}//removepublic 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{@Overridepublic void update(Object object) {System.out.println("Task1 get " + object);}
}//观察者2
class Task2 implements Observer{@Overridepublic void update(Object object) {System.out.println("Task2 get " + object);}
}
观察者模式的优点是:
- 符合开闭原则
- 可以在运行时建立对象之间的联系
应用:
- JDK
- java.util.Observable
- Spring
下面是Spring中的应用代码
//相当于上面案例的Observer
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {//相当于updatevoid onApplicationEvent(E var1);static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {return (event) -> {consumer.accept(event.getPayload());};}
}
他的发布者是ApplicationEventMulticaster