行为型模式(三):Observer ( 观察者模式 )

import java.util.ArrayList;
import java.util.List;

//被观察者接口
interface Watched{
public void addWatcher(Watcher watcher);
public void removeWatcher(Watcher watcher);
public void notifyAllWatchers(String str);
}
//被观察者实现类
class ConcreteWatched implements Watched{
List<Watcher> watchers=new ArrayList<Watcher>();
@Override//添加观察者
public void addWatcher(Watcher watcher) {
watchers.add(watcher);
}
@Override//通知观察者
public void notifyAllWatchers(String str) {
for(Watcher watcher:watchers){
watcher.update(str);
}
}
@Override//删除观察者
public void removeWatcher(Watcher watcher) {
watchers.remove(watcher);
}
}
//观察者接口
interface Watcher{
public void update(String str);
}
//观察者实现类
class ConcreteWatcher implements Watcher{
@Override//观察者动作
public void update(String str) {
System.out.println(str);
}
}


public class Test {
public static void main(String[] args) {
Watched girl=new ConcreteWatched();
Watcher boy1=new ConcreteWatcher();
Watcher boy2=new ConcreteWatcher();
Watcher boy3=new ConcreteWatcher();
girl.addWatcher(boy1);
girl.addWatcher(boy2);
girl.addWatcher(boy3);
girl.notifyAllWatchers("很开心~~~");
girl.removeWatcher(boy2);
girl.notifyAllWatchers("不开心~~~~");
}
}
posted @ 2012-01-08 19:46  一直在等  阅读(308)  评论(0编辑  收藏  举报