听人问起这个就上网搜了个例子,然后照葫芦画瓢自己也写了一个,大家帮忙看看有什么问题.public class Child {
private ArrayList eventList=new ArrayList();
private boolean isCry;

public void cry(){
isCry=true;
System.out.println("孩子哭了,声音很大");
ChildEvent childEvent =new ChildEvent(this,isCry);
fireChildEvent(childEvent);
}
public void addChildListener(ChildListener childListener){
eventList.add(childListener);
}
public void removeChildListener(ChildListener childListener){
eventList.remove(childListener);
}
private void fireChildEvent(ChildEvent childEvent){
for(int i=0;i<eventList.size();i++){
((ChildListener)eventList.get(i)).beWaked(childEvent);
}
}
public boolean isCry() {
return isCry;
}
public void setCry(boolean isCry) {
this.isCry = isCry;
}
}public class ChildEvent {
private Child child;
private boolean isCry;
public ChildEvent(Child child, boolean isCry) {
this.child = child;
this.isCry = isCry;
}
public void keepOnCry(){
//child.setCry(true);
System.out.println("孩子的哭声越来越大了!!!");
}
public void stopCry(){
child.setCry(false);
System.out.println("孩子吃完奶安静的睡了!!!");
}

}public interface ChildListener {
public void beWaked(ChildEvent e);
}class Father implements ChildListener{ public void beWaked(ChildEvent e) {
// TODO Auto-generated method stub
keepOnSleep();
e.keepOnCry();
}

private void keepOnSleep(){
System.out.println("爸爸被孩子的哭声吵醒了,但是又接着睡去");
}
}class Mother implements ChildListener{ public void beWaked(ChildEvent e) {
// TODO Auto-generated method stub
nurse();
e.stopCry();
} private void nurse(){
System.out.println("妈妈被孩子的哭声叫醒,起来给孩子喂奶");
}
// Motherther may have other methods to stop the child crying
}我现在有些问题,说了是照葫芦画瓢写的,如果程序本身是正确的,请帮再分析一下流程.多用专业术语,谢谢
还有个问题是Event中包含Child,和isCry (照例子写的),为什么这样写?只有child对象进来不行吗?
Event到底是不是像我写的这样是监听者处理的结果 还是?

解决方案 »

  1.   

    事件驱动是首先对某个事件建立监听器,然后当事件发生时候,相应事件的监听器会操作,来执行具体的操作,最后返回需要的数据。使用事件驱动的模型,主要是操作可以比较快得被响应,同时,同一个事件可以动态地被多个监听器操作,在做功能修改的时候,只需要改变监听器就可以,对被监听方的代码不需要做改变。这个也可以用在准实时的应用上。在传递参数上,尽量使用Object对象,或是自己定义的参数类型,因为事件分发者要处理的是通用的事件和参数,象上面那样的固定参数在实际中就有问题。
      

  2.   

    能不能具体解释下在这个例子中"事件"是谁?
    监听器到底是Listener接口还是实现接口的类?
    "准实时的应用"这个的意思是?
    "事件分发者"又是谁?
    谢谢,看来分都是您的,发了快一天了都没人回,呵呵