用处:aop,钩子函数,监听器,...
先上类图
案例代码
先定义监听者接口
package com.wwj.observermode;
public interface Listener {
public void action(Event event);
}
定义接口传入的事件源(需要的时候可以拿到当前监听的对象)
package com.wwj.observermode;
public class Event {
private Object source = null;
public Event(Object source){
source = source;
}
public Object getSource(){
return source;
};
public void setSource(Object o){
source = o;
}
}
开始写具体代码,先定义猫的实体类,跳的时候触发钩子函数
package com.wwj.observermode;
import java.util.ArrayList;
import java.util.List;
public class Cat {
//添加监听者集合
List<Listener> listeners = new ArrayList<>();
public Cat(){
this.addListener(new WaterListener());
this.addListener(new FoodListener());
}
//猫来回跳需要喂食喂水
public void jump(){
Event event = new Event(this);
for(Listener listener:listeners){
listener.action(event);
}
}
//添加监听者
public void addListener(Listener listener){
listeners.add(listener);
}
}
定义两个具体的监听者
package com.wwj.observermode;
public class FoodListener implements Listener {
@Override
public void action(Event event) {
Object source = event.getSource();
Cat cat = (Cat)source;
System.out.println("喂食物");
}
}
package com.wwj.observermode;
public class WaterListener implements Listener{
@Override
public void action(Event event) {
Object source = event.getSource();
Cat cat = (Cat)source;
System.out.println("喂水");
}
}
这样,调用猫的跳的动作时会触发要去喂水和喂食,耦合度低
package com.wwj.observermode;
public class main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.jump();
}
}
后续再新增钩子函数就比较方便了。