具体观察者角色:该角色实现抽象观察者角色所要求的更新接口,以便使本身的状态与主题的状态相协调。通常用一个子类实现。如果需要,具体观察者角色可以保存一个指向具体主题角色的引用。
以下是示例代码:
/** * 抽象主题角色 * @author dream * */ public interface Watched { public void addWatcher(Watcher watcher); public void remWatcher(Watcher watcher); public void notifyWatcher(String str); }
/** * 抽象观察者角色 * @author dream * */ public interface Watcher { public void update(String str); }
/** * 具体主题角色 * @author dream * */ public class SpecifcWatched implements Watched { public List<Watcher> list = new ArrayList<Watcher>(); @Override public void addWatcher(Watcher watcher) { // TODO Auto-generated method stub list.add(watcher); } @Override public void remWatcher(Watcher watcher) { // TODO Auto-generated method stub list.remove(watcher); } @Override public void notifyWatcher(String str) { // TODO Auto-generated method stub int len = list.size(); for(int t=0; t<len; ++t){ Watcher watcher = list.get(t); watcher.update("update"); } } }
/** * 具体观察者角色 * @author dream * */ public class SpecifcWatcher implements Watcher{ String name; public SpecifcWatcher(String name) { this.name = name; } @Override public void update(String str) { // TODO Auto-generated method stub System.out.println(name+":"+str); } }
/** * 测试观察者模式 * @author dream * */ public class Test { public static void main(String[] args) { Watched watched = new SpecifcWatched(); watched.addWatcher(new SpecifcWatcher("zhangsan")); //添加观察者 watched.addWatcher(new SpecifcWatcher("lisi")); watched.notifyWatcher("update"); //通知观察者变化 } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u012432475/article/details/47271727