【设计模式】观察者(Observer)模式
1.简介
观察者模式是行为型模式
的一种,其本生代表着一种一对多(one to many)
的关系:
当一个对象(目标对象)的状态发生改变时,所有依赖对象(观察者对象)都获得通知。
通常来讲,如果观察者对象过多或者通知一个观察者耗时太久,建议异步执行。同时,Java已经内置了观察者类/接口,可以继承。
2.特点
低耦合(loose coupling)
一对多(one to many)
3.例子
定义目标对象
@Data
@Component
class SendWeatherInfo extends Observable{
private WeatherInfo weatherInfo;
public void send(){
this.setChanged(); //使用内置观察者接口,必须先调用此方法
this.notifyObservers();
}
}
定义观察者对象
@Component
@slf4j
public WeatherCompany implements Observer{
private ExecutorService executorService = Executors.newFixedThreadPool(5);
@Override
public void update(Observable o, Object arg) {
executorService.execute(()->{
if(o instanceof SendWeatherInfo){
log.info("notice!!")
}
})
}
定义消息发送器
@Component
@EnableAsync
class MessageSender{
@Autowried
private SendWeatherInfo sendWeatherInfo;
@Autowried
private WeatherCompany weatherCompany;
@Async
public void sendMessage(WeatherInfo info){
sendWeatherInfo.setWeatherInfo(info);
sendWeatherInfo.addObserver(weatherCompany);
sendWeatherInfo.send();
}
}
}