package cn.test; import java.util.ArrayList; import java.util.List; public class Test01 { public static void main(String[] args) { WakeupEvent e = new WakeupEvent(); Child c = new Child(); c.setE(e); // c.addWakeupListener(new Father()); // c.wakeUp(); c.addWakeupListener(new Mother()); c.wakeUp(); } } /** * 爸爸实现了监听者 * @author Administrator * */ class Father implements WakeupListener{ @Override public void actionToWakeup(WakeupEvent arg0) { System.out.println("爸爸监听到了醒来,抱抱"); } } /** * 妈妈实现了监听者 * @author Administrator * */ class Mother implements WakeupListener{ @Override public void actionToWakeup(WakeupEvent arg0) { System.out.println("妈妈监听到了醒来,喂奶"); } } /** * 事件源 * @author Administrator * */ class Child { private WakeupEvent e ; /** * 添加醒来这件事 * @param e */ public void setE(WakeupEvent e) { this.e = e; } private List<WakeupListener> list = new ArrayList<WakeupListener>(); /** * 添加监听者 * @param l */ public void addWakeupListener(WakeupListener l){ this.list.add(l); } /** * 对监听做执行 */ public void wakeUp(){ for(WakeupListener wl:list){ if(e!=null){ wl.actionToWakeup(e); } } } } /** * 醒来的监听,监听器 * @author Administrator * */ interface WakeupListener{ /** * 监听醒来这件事 * @param e */ public void actionToWakeup(WakeupEvent e); } /** * * @author Administrator * 事件,醒来这件事 */ class WakeupEvent{ private int time ; private String loc ; private Object source ; public int getTime() { return time; } public void setTime(int time) { this.time = time; } public String getLoc() { return loc; } public void setLoc(String loc) { this.loc = loc; } public Object getSource() { return source; } public void setSource(Object source) { this.source = source; } }