首先定义事件接口,里面包含对几种事情类型的常量定义。
public interface EventSource {
public final int EVENT_TRUNON = 0x0;
public final int EVENT_TRUNOFF = 0x1;
public int getEventType();
}
然后定义一个具体的事件类型。
public class CookerEvent implements EventSource {
private String name;
private int level;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
@Override
public int getEventType(){
return EventSource.EVENT_TRUNON;
}
}
接着定义一个事件监听器的接口:
public interface EventListener {
/**
* 事件处理回调
*/
public void eventDispatched(CookerEvent event);
/**
* 事件类型是否匹配
*
* @param eventType
* @return
*/
public boolean isRightEventType(int eventType);
}
然后再定义一个事件监听器的基类
public abstract class CookerEventListener implements EventListener {
public abstract void cooker(String name, int level);
@Override
public void eventDispatched(CookerEvent event) {
cooker(event.getName(),event.getLevel());
}
@Override
public boolean isRightEventType(int eventType) {
return eventType == EventSource.EVENT_TRUNON;
}
}
再定义一个客户端方法,该方法将定义一个addEventListener()方法将监听对象加入一个列表,然后执行相应的操作。
public class CookerClient {
private List<CookerEventListener> listener = new ArrayList<CookerEventListener>();
public void addCookerEventListener(CookerEventListener cookerEventListener){
this.listener.add(cookerEventListener);
}
public void excute(String name,int level){
for(CookerEventListener cookerEventListener:listener){
CookerEvent event = new CookerEvent();
event.setName("处理过的:"+name);
event.setLevel(level);
cookerEventListener.eventDispatched(event);
}
}
}
excute()方法里的代码表明,在执行完一部分操作后,调用监听器的事件分发(eventDispatched)方法,该方法通过多态的形式分别调用不同监听器子类的cooker()方法。
接下来,我们分别实现两个监听器的子类,用于监听到事件后要执行的动作,如下:
public class MyCookerEvent extends CookerEventListener {
@Override
public void cooker(String name, int level) {
System.out.println("myCookerEvent: name=" + name + ",level=" + level);
}
}
另一个监听器子类:
public class HisCookerEvent extends CookerEventListener {
private String time;
HisCookerEvent(String time){
this.time = time;
}
@Override
public void cooker(String name, int level) {
System.out.println("hisCookerEvent: name=" + name + ",level=" + level + ",his time is:" + this.time + "ms.");
}
public void setTime(String time) {
this.time = time;
}
public String getTime() {
return time;
}
}
调用的代码如下:
public static void main(String[] args) {
CookerClient cookerClient = new CookerClient();
/*加入两个监听器*/
cookerClient.addCookerEventListener(new MyCookerEvent());
cookerClient.addCookerEventListener(new HisCookerEvent("30"));
/*执行客户端调用,满足一定条件后通知上面的两个监听器*/
cookerClient.excute("haha",2);
}
Java监听器Listener
最新推荐文章于 2020-08-15 06:06:16 发布