目录
1.定义
观察者模式(Observer Pattern)定义了对象之间一对多依赖,让多个观察者同时监听一个主体对象,当主体对象发生变化时,它的所有依赖者(观察者)都会收到通知并更新。(也叫发布订阅模式)
2.适用场景
- 观察者模式主要用于在关联行为之间建立一套触发机制的场景。
3.案例一:在学习平台提问时@老师
(使用JDK提供的Observer类来实现观察者模式)
UML类图
代码实现
Study 类
public class Study extends Observable {
private String name = "study学习平台";
private static Study study = null;
private Study() {}
public static Study getInstance() {
if (null == study) {
study = new Study();
}
return study;
}
public String getName() {
return name;
}
public void publishQuestion(Question question) {
System.out.println(question.getUserName() + "在" + this.name + "上提交了一个问题。");
setChanged();
notifyObservers(question);
}
}
Teacher 类
public class Teacher implements Observer {
private String name;
public Teacher(String name) {
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
Study study = (Study) o;
Question question = (Question) arg;
System.out.println("==========================================");
System.out.println(name + "老师,你好!\n" +
"您收到了一个来自“" + study.getName() + "”的提问,希望您解答,问题内容如下:\n" +
question.getContent() + "\n" +
"提问者是:" + question.getUserName());
}
}
Question 类
public class Question {
private String userName;
private String content;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
测试类
public class ObserverTest {
public static void main(String[] args) {
Study study = Study.getInstance();
Teacher tom = new Teacher("Tom");
Teacher mic = new Teacher("Mic");
// 这位同学没有@Tom老师,所以没有收到
// 要先@老师再发布
Question question = new Question();
question.setUserName("小明");
question.setContent("观察者设计模式适用于那些场景呢?");
study.addObserver(tom);
study.addObserver(mic);
study.publishQuestion(question);
}
}
输出结果:
小明在study学习平台上提交了一个问题。
==========================================
Mic老师,你好!
您收到了一个来自“study学习平台”的提问,希望您解答,问题内容如下:
观察者设计模式适用于那些场景呢?
提问者是:小明
==========================================
Tom老师,你好!
您收到了一个来自“study学习平台”的提问,希望您解答,问题内容如下:
观察者设计模式适用于那些场景呢?
提问者是:小明
4.案例二:鼠标点击监听时间
(自己动手写观察者模式)
UML类图
代码实现
Event 类
public class Event {
// 事件源,事件是由谁发起的保存起来
private Object source;
// 事件触发,要通知谁
private Object target;
// 事件触发,要做什么动作,回调
private Method callback;
// 事件的名称,触发的是什么事件
private String trigger;
// 事件触发的时间
private long time;
public Event(Object target, Method callback) {
this.target = target;
this.callback = callback;
}
public Event setSource(Object source) {
this.source = source;
return this;
}
public Event setTime(long time) {
this.time = time;
return this;
}
public Object getSource() {
return source;
}
public Event setTrigger(String trigger) {
this.trigger = trigger;
return this;
}
public long getTime() {
return time;
}
public Object getTarget() {
return target;
}
public Method getCallback() {
return callback;
}
@Override
public String toString() {
return "Event{" + "\n" +
"\tsource=" + source.getClass() + ",\n" +
"\ttarget=" + target.getClass() + ",\n" +
"\tcallback=" + callback + ",\n" +
"\ttrigger='" + trigger + "',\n" +
"\ttime=" + time + "'\n" +
'}';
}
}
EventListener 类
public class EventLisenter {
//JDK底层的Lisenter通常也是这样来设计的
protected Map<String,Event> events = new HashMap<String,Event>();
/**
* 事件名称和一个目标对象来触发事件
*/
public void addLisenter(String eventType,Object target){
try {
if (Objects.nonNull(target)) {
this.addLisenter(
eventType,
target,
target.getClass().getMethod("on" + toUpperFirstCase(eventType), Event.class));
}
}catch (Exception e){
e.printStackTrace();
}
}
public void addLisenter(String eventType, Object target, Method callback){
// 注册事件
events.put(eventType, new Event(target, callback));
}
/**
* 触发,只要有动作就触发
*/
private void trigger(Event event) {
event.setSource(this);
event.setTime(System.currentTimeMillis());
try {
//发起回调
if(event.getCallback() != null){
//用反射调用它的回调函数
event.getCallback().invoke(event.getTarget(),event);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 事件名称触发
*/
protected void trigger(String trigger){
if(this.events.containsKey(trigger)){
trigger(this.events.get(trigger).setTrigger(trigger));
}
}
/**
* 逻辑处理的私有方法,首字母大写
*/
private String toUpperFirstCase(String str){
char[] chars = str.toCharArray();
chars[0] -= 32;
return String.valueOf(chars);
}
}
Mouse 类
public class Mouse extends EventLisenter {
public void click(){
System.out.println("调用单击方法");
this.trigger(MouseEventTypeEnum.ON_CLICK.value());
}
public void blur(){
System.out.println("调用失焦方法");
this.trigger(MouseEventTypeEnum.ON_BLUR.value());
}
}
MouseEventCallback 类
public class MouseEventCallback {
public void onClick(Event e){
System.out.println("===========触发鼠标单击事件==========" + "\n" + e);
}
public void onBlur(Event e){
System.out.println("===========触发鼠标失焦事件==========" + "\n" + e);
}
}
MouseEventTypeEnum 枚举类
public enum MouseEventTypeEnum {
//单击
ON_CLICK("click"),
//失焦
ON_BLUR("blur");
private String value;
MouseEventTypeEnum(String value) {
this.value = value;
}
public String value() {
return value;
}
}
测试类
public class MouseEventTest {
public static void main(String[] args) {
MouseEventCallback callback = new MouseEventCallback();
Mouse mouse = new Mouse();
// 提问前@谁?? @回调方法
mouse.addLisenter(MouseEventTypeEnum.ON_CLICK.value(), callback);
mouse.addLisenter(MouseEventTypeEnum.ON_BLUR.value(), callback);
// 提问
mouse.click();
mouse.blur();
}
}
输出结果:
调用单击方法
===========触发鼠标单击事件==========
Event{
source=class com.gupaoedu.vip.pattern.observer.events.mouseevent.Mouse,
target=class com.gupaoedu.vip.pattern.observer.events.mouseevent.MouseEventCallback,
callback=public void com.gupaoedu.vip.pattern.observer.events.mouseevent.MouseEventCallback.onClick(com.gupaoedu.vip.pattern.observer.events.core.Event),
trigger='click',
time=1584795481567'
}
调用失焦方法
===========触发鼠标失焦事件==========
Event{
source=class com.gupaoedu.vip.pattern.observer.events.mouseevent.Mouse,
target=class com.gupaoedu.vip.pattern.observer.events.mouseevent.MouseEventCallback,
callback=public void com.gupaoedu.vip.pattern.observer.events.mouseevent.MouseEventCallback.onBlur(com.gupaoedu.vip.pattern.observer.events.core.Event),
trigger='blur',
time=1584795481567'
}
5.案例三:使用Guava实现
GuavaEvent 类
public class GuavaEvent {
@Subscribe
public void subscribe(String str) {
System.out.println("执行subscribe方法,传入的参数是:" + str);
}
}
测试类:
public class GuavaEventTest {
public static void main(String[] args) {
// 消息总线
EventBus eventBus = new EventBus();
GuavaEvent guavaEvent = new GuavaEvent();
eventBus.register(guavaEvent);
eventBus.post("Tom");
}
}
输出结果:
执行subscribe方法,传入的参数是:Tom
5.在源码中的体现
Spring中的ContextLoaderListener、ApplicationContextAware等对象就是用了观察者模式,当你看到Listener后缀的时候,一般就是在使用观察者模式。
ContextLoaderListener
Spring 中的 ContextLoaderListener 实现了 ServletContextListener 接口,ServletContextListener 接口又继承了 EventListener,在 JDK 中 EventListener 有非常广泛的应用。我们可以看一下源代码:
package org.springframework.web.context;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
public void contextInitialized(ServletContextEvent event) {
this.initWebApplicationContext(event.getServletContext());
}
public void contextDestroyed(ServletContextEvent event) {
this.closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}
6.观察者模式的优点
- 观察者和被观察者之间建立了一个抽象的耦合;
- 观察者模式支持广播通信。
7.观察者模式的缺点
- 观察者之间有过多的细节依赖、提高时间消耗及程序的复杂度;
- 使用要得当,要避免循环调用。