标签:list override ati erp out rgs code event ack
javaWeb中的Listener中涉及到了监听器模式,所以回来补充一下
监听器模式用来监听某个对象发生的事件,当此对象发生被监听的事件后,监听器的某个方法将被执行,其主要组成有: 事件源,事件监听器,事件对象
监听器模式很简单,直接看代码就能理解,这里举例监听小狗的玩和学习事件
public class Event {
// 存放事件源的引用
Object object;
public Event(Object object) {
super();
this.object = object;
}
public Object getObject() {
return object;
}
}
狗的监听器接口
public interface DogListener {
public void playListener(Event event);
public void studyListener(Event event);
}
狗监听器的实现类
package listenerpatten;
public class MyDogListener implements DogListener {
@Override
public void playListener(Event event) {
System.out.println("监听器:监听到" + event.getObject().getClass().getName() + "在玩");
}
@Override
public void studyListener(Event event) {
System.out.println("监听器:监听到" + event.getObject().getClass().getName() + "在学习");
}
}
public class Dog {
private MyDogListener myDogListener;
public void setDogListener(MyDogListener myDogListener) {
this.myDogListener = myDogListener;
}
public void play(){
System.out.println("Dog: i am playing");
Event event = new Event(this);
myDogListener.playListener(event);
}
public void study(){
System.out.println("Dog: i am studying");
Event event = new Event(this);
myDogListener.studyListener(event);
}
}
public class test {
public static void main(String[] args) {
Dog dog = new Dog();
MyDogListener myDogListener = new MyDogListener();
dog.setDogListener(myDogListener);
dog.play();
dog.study();
}
}
Dog: i am playing
监听器:监听到listenerpatten.Dog在玩
Dog: i am studying
监听器:监听到listenerpatten.Dog在学习
标签:list override ati erp out rgs code event ack
原文地址:https://www.cnblogs.com/Howlet/p/12325646.html