话不多说,上代码:
package test;
import java.util.EventListener;
import java.util.EventObject;
import java.util.List;
import java.util.Vector;
class EventClassOne extends EventObject{
public EventClassOne(Object source) {
super(source);
}
}
class EventSource{
public String name;
public EventSource(String name){
this.name=name;
}
// 存储事件监听器的篮子
Vector listeners=new Vector();
// 把事件监听器加到篮子里
public void addEventListener(EventListener e){
listeners.add(e);
}
// 触发事件的动作
public void say(String s){
for (int i = 0; i <listeners.size() ; i++) {
((MyEventListener)listeners.elementAt(i))
.action(new EventClassOne(this));
}
}
}
class MyEventListener implements EventListener {
public void action(EventObject eventObject){
if(eventObject.getSource() instanceof EventSource){
String name = ((EventSource) eventObject.getSource()).name;
System.out.println(name+",喊什么喊,吵到人家做爱了");
}
}
}
public class EventTest {
public static void main(String[] args) {
EventSource 小凤=new EventSource("小凤");
EventSource 巨柱=new EventSource("巨柱");
MyEventListener listener1=new MyEventListener();
MyEventListener listener2=new MyEventListener();
小凤.addEventListener(listener1);
小凤.addEventListener(listener2);
巨柱.addEventListener(listener1);
小凤.say("想要个猛男");
巨柱.say("想要个美女");
}
}
结果:
"C:Program FilesJavajdk1.8.0_171injava.exe"
小凤,喊什么喊,吵到人家做爱了
小凤,喊什么喊,吵到人家做爱了
巨柱,喊什么喊,吵到人家做爱了
Process finished with exit code 0