水果已经卖完了,顾客不知道什么时候到货,又不可能天天过来看一下有没有到货,这就需要水果店这边通知顾客
image.png
观察者模式
image.png可以看到观察者模式中,需要添加观察你的对象或者删除观察你的对象,这就需要一个容器,然后每当被观察者发生变化时,需要遍历通知容器中的所有观察者。
//被观察者
public abstract class Observable{
//关注客户列表
protected List<Observer> observers = new ArrayList();
//关注顾客
public void add(Observer observer) {
observers.add(observer);
}
//取消关注
public void remove(Observer observer) {
observers.remove(observer);
}
//发通知
public abstract void notifyObservers();
}
//观察者
public interface Observer {
void update();
}
public class MangoAttention extends Attentions{
@Override
public void notifyObservers() {
//遍历观察者集合,调用每一个顾客的购买方法
for(Observer obs : observers) {
obs.update();
}
}
}
public class CustomerObserver implements Observer {
private String name;
public CustomerObserver(String name){
this.name = name;
}
@Override
public void update() {
System.out.println(name + "购买青芒");
}
}
/**
* 观察者模式
* 顾客关注了芒果,降价时通知他们
*/
public class ObserverClient {
public static void main(String[] args) {
MangoAttention attentions = new MangoAttention();//目标
attentions.add(new CustomerObserver("1"));
attentions.add(new CustomerObserver("2"));
attentions.add(new CustomerObserver("3"));
attentions.add(new CustomerObserver("4"));
//到货
attentions.notifyObservers();
}
}
总结
- 观察者模式是非常常用的模式,将客户端请求服务端的方式反转为服务端通知客户端,这样做可以很好的解耦,而且不需要客户端时时刻刻去关注服务端,在消息通知中很常用
网友评论