设计模式-观察者模式
别名:发布-订阅模式
定义了多个订阅者监听某个发布者的一对多依赖关系,当发布者发布消息时订阅者会被通知并自主处理状态变化。
看代码
我们先定义 Subject 和 Observer
public interface Observer {
void update(Object obj);
}
public abstract class Subject {
private List<Observer> observers = new ArrayList<>();
public void addOb(Observer ob){
observers.add(ob);
}
public void removeOb(Observer ob){
observers.remove(ob);
}
public void notifyObs(Object obj){
observers.forEach(observer -> observer.update(obj));
}
}
比如疫情期间,娱乐设施是否营业需要遵循政府的规定
在这个例子中政府就是发布方
public class Government extends Subject {
private boolean canBusiness = true;
public void startBusiness(){
this.canBusiness = true;
notifyObs(canBusiness);
}
public void closeBusiness(){
this.canBusiness = false;
notifyObs(canBusiness);
}
}
而订阅者就是娱乐场馆
public class Entertainment implements Observer {
@Override
public void update(Object obj) {
boolean msg = (boolean) obj;
if (msg) {
System.out.println("开始营业");
} else {
System.out.println("暂停营业");
}
}
}
这样娱乐场馆就可以自动处理政府发布的政令了
public class Ordain {
public static void main(String[] args) {
Government government = new Government();
Observer entertainment = new Entertainment();
government.addOb(entertainment);
government.closeBusiness();
government.startBusiness();
}
}
观察者模式可以将发布者与订阅者解耦,变化与迭代都更加的灵活