一、概述
childe类中的是关联监听者dad的,若要再增加监听者,会很不方便,且要修改代码。好的方法是封装监听者类,用addListener()方法动态添加监听者
二、代码
1.Test.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | class WakenUpEvent{ private long time; private String location; private Child source; public WakenUpEvent( long time, String location, Child source) { super (); this .time = time; this .location = location; this .source = source; } public long getTime() { return time; } public void setTime( long time) { this .time = time; } public String getLocation() { return location; } public void setLocation(String location) { this .location = location; } public Child getSource() { return source; } public void setSource(Child source) { this .source = source; } } class Child implements Runnable { private List<WakenUpListener> wakenUpListeners = new ArrayList<WakenUpListener>(); public void addWakenUpListener(WakenUpListener wul){ wakenUpListeners.add(wul); } public void wakeUp(){ for ( int i = 0 ; i < wakenUpListeners.size(); i++){ WakenUpListener l = wakenUpListeners.get(i); l.actionToWakenUp( new WakenUpEvent(System.currentTimeMillis(), "bed" , this )); } } @Override public void run() { try { Thread.sleep( 3000 ); } catch (Exception e) { e.printStackTrace(); } wakeUp(); } } interface WakenUpListener { public void actionToWakenUp(WakenUpEvent e); } class Dad implements WakenUpListener { public void actionToWakenUp(WakenUpEvent e) { System.out.println( "Fedd the child" ); } } class GrandFather implements WakenUpListener { public void actionToWakenUp(WakenUpEvent e) { System.out.println( "抱孩子" ); } } public class Test { public static void main(String[] args) { Child c = new Child(); c.addWakenUpListener( new Dad()); c.addWakenUpListener( new GrandFather()); new Thread(c).start(); } } |
三、运行结果