方式三:更具备通用性,添加监听事件(让多个人同时监听小孩醒来这个事件并作出相应动作,dad和mom就是观察者)
class Dad implements WakeUpActionListener{ @Override public void wakeUpAction(WakeUpEvent wakeUpEvent) { System.out.println("爸爸给小孩喂奶。。。"); } } class Mom implements WakeUpActionListener{ @Override public void wakeUpAction(WakeUpEvent wakeUpEvent) { System.out.println("妈妈给小孩喂奶"); } } class WakeUpEvent{ } interface WakeUpActionListener{ void wakeUpAction(WakeUpEvent wakeUpEvent); } class Child implements Runnable{ private List<WakeUpActionListener> listenerLists=new ArrayList<WakeUpActionListener>(); void addListener(WakeUpActionListener l){ listenerLists.add(l); } void wakeUp(){ System.out.println("醒来了"); for(WakeUpActionListener l:listenerLists){ l.wakeUpAction(new WakeUpEvent()); } } @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } wakeUp(); } } public class Test { public static void main(String[] args){ Dad d=new Dad(); Mom m=new Mom(); Child c=new Child(); c.addListener(d); c.addListener(m); new Thread(c).start(); } }
用属性文件管理Observers
文件名observer.properties,里面内容:observers=ObserverMode.Dad,ObserverMode.Mom将上面代码部分的main函数换成以下
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException{ Child c=new Child(); Properties props=new Properties(); //如果文件放在src下直接可以写文件名,如果放在包下写上路径 props.load(Test.class.getClassLoader().getResourceAsStream("ObserverMode/observer.properties")); String[] observers=props.getProperty("observers").split(","); for(String observer:observers){ c.addListener((WakeUpActionListener)Class.forName(observer).newInstance()); } new Thread(c).start(); }