本质就是有很多哥们看着一个哥们,这哥们发生了个啥动作,看着他的哥们就要执行对应的动作。 和责任链模式很像但是它不能往回穿,应用的地方到处都是,spring的refresh方法里就有。 首先定义个观察者接口
public interface MyObserve {
void action(MyEvent myEvent);
}
定义两个实体:
public class Cat implements MyObserve {
@Override
public void action(MyEvent myEvent) {
System.out.println("猫猫捕鱼"+myEvent.getTime()+"小时");
}
}
public class Dog implements MyObserve {
@Override
public void action(MyEvent myEvent) {
System.out.println("狗狗散步"+myEvent.getTime()+"小时");
}
}
定义个事件类:
public class MyEvent {
private Long time;
private Weather weather;
public MyEvent(){
}
public MyEvent(Long time, Weather weather) {
this.time = time;
this.weather = weather;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
public Weather getWeather() {
return weather;
}
public void setWeather(Weather weather) {
this.weather = weather;
}
}
定义个被观察者:
public class Weather {
private boolean fine = false;
private List<MyObserve> observes = new ArrayList<>();
public Weather addObserve(MyObserve observe){
observes.add(observe);
return this;
}
public boolean isFine(){
return fine;
}
public void fineWeather(){
fine = true;
for (MyObserve observe : observes) {
observe.action(new MyEvent(5L,this));
}
}
}
执行:
public class Test1 {
public static void main(String[] args) {
Weather weather = new Weather();
weather.addObserve(new Dog()).addObserve(new Cat());
weather.fineWeather();
}
}