IWatched:
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午4:58:25 */public interface IWatched { public void addWatcher(IWatcher watcher); public void removeWatcher(IWatcher watcher); public void notifyWatchers(String msg);}
IWatcher:
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午4:55:23 */public interface IWatcher { public void update(String msg);}
Watched:
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午5:01:05 */public class Watched implements IWatched{ private Listwatchers = new ArrayList (); @Override public void addWatcher(IWatcher watcher) { watchers.add(watcher); } @Override public void removeWatcher(IWatcher watcher) { watchers.remove(watcher); } @Override public void notifyWatchers(String msg) { for(IWatcher watcher : watchers){ watcher.update(msg); } }}
Watcher:
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午5:04:56 */public class Watcher implements IWatcher{ @Override public void update(String msg) { System.out.println(msg); }}
Test:
/** * @author com.tiantian * @version 创建时间:2012-11-20 下午5:05:26 */public class Test { public static void main(String[] args) { IWatched watched = new Watched(); IWatcher watcher1 = new Watcher(); IWatcher watcher2 = new Watcher(); IWatcher watcher3 = new Watcher(); watched.addWatcher(watcher1); watched.addWatcher(watcher2); watched.addWatcher(watcher3); watched.notifyWatchers("I have been clicked!"); watched.removeWatcher(watcher1); watched.notifyWatchers("what's up"); }}