观察者模式的应用场景
观察者模式(Observer Pattern)定义了对象之间的一对多依赖,让多个观察者对象同时监听一个主体对象,当主体对象发生变化时,它的所有以依赖者(观察者)都会受到通知并更新,属于行为型模式。
观察者模式有时也叫作发布订阅模式。观察者模式主要用于在关联行为之间建立一套触发机制的场景。观察者模式在现实生活应用得也非常广泛,比如微信朋友圈动态通知、页面的消息通知、邮件通知、广播通知等。
JDK API
当“小伙伴们”在 GPer 生态圈中提问的时候,如果设置了指定老师回答,对应的老师就会收到邮件通知,这就是观察者模式的一种应用场景。其实 JDK 本身就提供了这样的 API。我们用代码来还原一下这个应用场景,创建 GPer 类:
package com.yjw.demo.pattern.observer.GPer_java;
import java.util.Observable;
public class GPer extends Observable {
private String name = "GPer 生态圈";
private static GPer gper = null;
private GPer() {
}
public static GPer getInstance() {
if (null == gper) {
gper = new GPer();
}
return gper;
}
public String getName() {
return name;
}
public void publishQuestion(Question question) {
System.out.println(question.getUserName() + "在" + this.name + "上提交了一个问题。");
setChanged();
notifyObservers(question);
}
}
创建文体类 Question:
package com.yjw.demo.pattern.observer.GPer_java;
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;
}
}
创建老师类 Teacher:
package com.yjw.demo.pattern.observer.GPer_java;
import java.util.Observable;
import java.util.Observer;
public class Teacher implements Observer {
private String name;
public Teacher(String name) {
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
GPer gper = (GPer) o;
Question question = (Question) arg;
System.out.println("========================");
System.out.println(name + "老师,你好!\n" + "您收到了一个来自“" + gper.getName()
+ "”的提问,希望您解答,问题内容如下:\n" + question.getContent()
+ "\n" + "提问者:" + question.getUserName());
}
}
客户端测试代码如下:
package com.yjw.demo.pattern.observer.GPer_java;
public class ObserverTest {
public static void main(String[] args) {
GPer gper = GPer.getInstance();
Teacher tom = new Teacher("Tom");
Teacher mic = new Teacher("Mic");
gper.addObserver(tom);
gper.addObserver(mic);
// 业务逻辑代码
Question question = new Question();
question.setUserName("小明");
question.setContent("观察者设计模式适用于哪些场景?");
gper.publishQuestion(question);
}
}
运行结果如下图所示。
手动实现
为了更加深刻地了解观察者模式的实现原理,我们设计一个监听鼠标事件的观察者模式。
首先,创建 Event 类:
package com.yjw.demo.pattern.observer.mouse.core;
import java.lang.reflect.Method;
/**
* 事件内容
*/
public class Event {
// 事件源,事件由谁发起的,保存起来
private Object source;
// 事件触发,要通知谁
private Object target;
// 事件触发,要做什么动作,回调
private Method callback;
// 事件的名称,触发是什么事件
private String trigger;
// 事件触发的时间
private long time;
public Event(Object target, Method callback) {
super();
this.target = target;
this.callback = callback;
}
public Object getSource() {
return source;
}
public void setSource(Object source) {
this.source = source;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
public Method getCallback() {
return callback;
}
public void setCallback(Method callback) {
this.callback = callback;
}
public String getTrigger() {
return trigger;
}
public void setTrigger(String trigger) {
this.trigger = trigger;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
@Override
public String toString() {
return "Event{" +
"source=" + source +
", target=" + target +
", callback=" + callback +
", trigger='" + trigger + '\'' +
", time=" + time +
'}';
}
}
创建 EventLisenter 类:
package com.yjw.demo.pattern.observer.mouse.core;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* 监听器,它就是观察者的桥梁
*/
public class EventListener {
// JDK 底层的Listener通常也是这样设计的
private Map<String, Event> events = new HashMap<>();
/**
* 添加事件监听
*
* @param eventType
* @param target
*/
public void addListener(String eventType, Object target) {
try {
this.addListener(eventType, target,
target.getClass().getMethod("on" + toUpperFirstCase(eventType), Event.class));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public void addListener(String eventType, Object target, Method callback) {
// 注册事件
events.put(eventType, new Event(target, callback));
}
/**
* 触发事件
*
* @param event
*/
public 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();
}
}
/**
* 触发事件
*
* @param trigger
*/
protected void trigger(String trigger) {
if (!this.events.containsKey((trigger))) {
return;
}
trigger(this.events.get(trigger).setTrigger(trigger));
}
private String toUpperFirstCase(String str) {
char[] chars = str.toCharArray();
chars[0] -= 32;
return String.valueOf(chars);
}
}
创建 MouseEventType 接口:
package com.yjw.demo.pattern.observer.mouse;
/**
* 鼠标事件类型
*/
public interface MouseEventType {
// 单击
String ON_CLICK = "click";
// 双击
String ON_DOUBLE_CLICK = "doubleClick";
// 弹起
String ON_UP = "up";
// 按下
String ON_DOWN = "down";
// 移动
String ON_MOVE = "move";
// 滚动
String ON_WHEEL = "wheel";
// 悬停
String ON_OVER = "over";
// 失焦
String ON_BLUR = "blur";
// 获焦
String ON_FOCUS = "focus";
}
创建 Mouse 类:
package com.yjw.demo.pattern.observer.mouse;
import com.yjw.demo.pattern.observer.mouse.core.EventListener;
/**
* 鼠标
*
* <pre>
* 通常的话,采用动态代理来实现监控,避免了代码侵入
* </pre>
*
* @author yinjianwei
* @date 2019/01/04
*/
public class Mouse extends EventListener {
public void click() {
System.out.println("调用单击方法");
trigger(MouseEventType.ON_CLICK);
}
public void doubleClick() {
System.out.println("调用双击方法");
trigger(MouseEventType.ON_DOUBLE_CLICK);
}
public void up() {
System.out.println("调用弹起方法");
trigger(MouseEventType.ON_UP);
}
public void down() {
System.out.println("调用按下方法");
trigger(MouseEventType.ON_DOWN);
}
public void move() {
System.out.println("调用移动方法");
trigger(MouseEventType.ON_MOVE);
}
public void wheel() {
System.out.println("调用滚动方法");
trigger(MouseEventType.ON_WHEEL);
}
public void over() {
System.out.println("调用悬停方法");
trigger(MouseEventType.ON_OVER);
}
public void blur() {
System.out.println("调用失焦方法");
trigger(MouseEventType.ON_BLUR);
}
public void focus() {
System.out.println("调用获焦方法");
trigger(MouseEventType.ON_FOCUS);
}
}
创建 MouseEventCallback 类:
package com.yjw.demo.pattern.observer.mouse;
import com.yjw.demo.pattern.observer.mouse.core.Event;
/**
* 观察者,观察鼠标动作
*
* @author yinjianwei
* @date 2019/01/04
*/
public class MouseEventCallback {
public void onClick(Event event) {
System.out.println("==========触发鼠标单击事件==========" + "\n" + event);
}
public void onDoubleClick(Event event) {
System.out.println("==========触发鼠标双击事件==========" + "\n" + event);
}
public void onUp(Event event) {
System.out.println("==========触发鼠标弹起事件==========" + "\n" + event);
}
public void onDown(Event event) {
System.out.println("==========触发鼠标按下事件==========" + "\n" + event);
}
public void onMove(Event event) {
System.out.println("==========触发鼠标移动事件==========" + "\n" + event);
}
public void onWheel(Event event) {
System.out.println("==========触发鼠标滚动事件==========" + "\n" + event);
}
public void onOver(Event event) {
System.out.println("==========触发鼠标悬停事件==========" + "\n" + event);
}
public void onBlur(Event event) {
System.out.println("==========触发鼠标失焦事件==========" + "\n" + event);
}
public void onFocus(Event event) {
System.out.println("==========触发鼠标获焦事件==========" + "\n" + event);
}
}
客户端测试代码如下:
package com.yjw.demo.pattern.observer.mouse;
import java.lang.reflect.Method;
import com.yjw.demo.pattern.observer.mouse.core.Event;
/**
* 鼠标事件测试
*
* @author yinjianwei
* @date 2019/01/04
*/
public class MouseEventTest {
public static void main(String[] args) {
try {
MouseEventCallback mouseEventCallback = new MouseEventCallback();
// 注册事件
Mouse mouse = new Mouse();
mouse.addListener(MouseEventType.ON_CLICK, mouseEventCallback);
mouse.addListener(MouseEventType.ON_DOUBLE_CLICK, mouseEventCallback);
mouse.addListener(MouseEventType.ON_UP, mouseEventCallback);
mouse.addListener(MouseEventType.ON_DOWN, mouseEventCallback);
mouse.addListener(MouseEventType.ON_MOVE, mouseEventCallback);
mouse.addListener(MouseEventType.ON_WHEEL, mouseEventCallback);
mouse.addListener(MouseEventType.ON_OVER, mouseEventCallback);
mouse.addListener(MouseEventType.ON_BLUR, mouseEventCallback);
mouse.addListener(MouseEventType.ON_FOCUS, mouseEventCallback);
// 调用方法
mouse.click();
mouse.doubleClick();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果如下图所示。
观察者模式的优缺点
观察者模式的优点如下:
- 在观察者和被观察者之间建立了一个抽象的耦合。
- 观察者模式支持广播通信。
观察者模式的缺点如下:
- 观察者之间有过多的细节依赖、时间消耗多,程序的复杂性更高。
- 使用不当会出现循环调用。
摘录:《Spring 5 核心原理与30个类手写实战》来自文艺界的Tom老师的书籍。
作者:殷建卫 链接:https://www.yuque.com/yinjianwei/vyrvkf/hfzxhi 来源:殷建卫 - 架构笔记 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。