问题
最近出的华为mate x卖的非常火爆,常常出现断货的情况。有些顾客为了买到mate x,每天都往店里跑来咨询是否有货,顾客很辛苦;当到货的时候,很多顾客没有来买,我只能挨家挨户的通知所有人到货了,你们快来买,店员很辛苦。既然这么辛苦的话,我们就相互减轻一点工作量。这就引入我们的观察者模式
简介
上述问题中描述的两种情况,都是计算机中常见的情形。了解的朋友一下就能知道,一个是轮询,另一个是广播。而轮询和广播都是非常消耗资源的(顾客和店员都很辛苦),在非必要的情况下,当然是尽量时避免轮询和广播的。而观察者模式就是采取订阅通知的方式来减少非必要的轮询和广播。生活中常见的例子就是订阅报纸。Android中的eventBus,后端的kafka,消息队列等都是典型的观察者模式例子。
实现
先构造顾客
public class Custom {
private String name;
public Custom(String name) {
this.name = name;
}
public void notify(String message) {
System.out.println(name + " got the message: " + message);
}
}
我的电脑城
public class Store {
private List<Custom> customList = new ArrayList<>();
public void addObserver(Custom custom) {
customList.add(custom);
}
public void goodsArrive() {
for (Custom custom : customList) {
custom.notify("huawei mate x has arrived");
}
}
}
执行代码
public static void main(String[] args) {
Store store = new Store();
Custom custom1 = new Custom("zhao");
Custom custom2 = new Custom("qian");
Custom custom3 = new Custom("sun");
Custom custom4 = new Custom("li");
Custom custom5 = new Custom("zhou");
store.addObserver(custom1);
store.addObserver(custom2);
store.addObserver(custom3);
store.addObserver(custom4);
store.addObserver(custom5);
store.goodsArrive();
}
执行结果
zhao got the message: huawei mate x has arrived
qian got the message: huawei mate x has arrived
sun got the message: huawei mate x has arrived
li got the message: huawei mate x has arrived
zhou got the message: huawei mate x has arrived
总结
实现方式比较简单,将希望订阅的客户添加到店铺的订阅名单,等到货之后,就顺序通知所有订阅顾客,顾客收到消息之后,就可以自行前往店铺购买。优点:节约资源,避免使用轮询和广播;单一职责,添加订阅者无需修改订阅对象;我们会在大量场景中需要使用此设计模式,但总不会这么简单,需要做一定的变化以适应不同的需求。