1. Java中Observer观察者模式
class="Watched.java" name="code">
public interface Watched{
public void addWatcher(Watcher watcher);
public void removeWatcher(Watcher watcher);
public void notifyWatchers(String str);
}
public interface Watcher{
public void update(String str);
}
public class ConcreteWatched implements Watched{
private List<Watcher> list = new ArrayList<Watcher>();
@Override
public void addWatcher(Watcher watcher){
list.add(watcher);
}
@Override
public void removeWatcher(Watcher watcher){
list.remove(watcher);
}
@Override
public void notifyWatchers(String str){
for(Watcher watcher : list){
watcher.update(str);
}
}
}
public 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 watcher1 = new ConcreteWatcher();
Watcher watcher2 = new ConcreteWatcher();
Watcher watcher3 = new ConcreteWatcher();
girl.addWatcher(watcher1);
girl.addWatcher(watcher2);
girl.addWatcher(watcher3);
girl.notifyWatchers("开心,爽");
girl.removeWatcher(watcher2);
girl.notifyWatchers("不爽");
}
}