个人理解:就是一个类拥有另一个类的引用 ,其中前者是被观察者,后者是观察者
当被观察者发生状态改变的时候,观察者发生变化。
1 观察者接口
public interface Watcher {
public void update( String str);
}
2 观察者接口的实现类
public class ConcreateWatcher implements Watcher{
@Override
public void update(String str) {
System.out.println("观察者收到 : " + str );
}
}
3 被观察者接口
public interface Watched {
public void addWatcher(Watcher watcher);
public void removeWatcher(Watcher watcher);
public void notifyWatchers(String str);
}
4 被观察者接口的实现类
public class concreateWatched implements Watched{
private List <Watcher> list = new ArrayList<Watcher>();
@Override
public void addWatcher(Watcher watcher) {
list.add(watcher);
}
@Override
public void notifyWatchers(String str) {
for(Watcher watcher :list ){
watcher.update(str);
}
}
@Override
public void removeWatcher(Watcher watcher) {
list.remove(watcher );
}
}
5 测试类
public class TestWatcher {
/**
* @param args
*/
public static void main(String[] args) {
//被观察者
Watched girl = new concreateWatched();
//创建三个 观察者
Watcher watcher1 = new ConcreateWatcher();
Watcher watcher2 = new ConcreateWatcher();
Watcher watcher3 = new ConcreateWatcher();
//被观察者中 添加观察者监听器
girl.addWatcher(watcher1);
girl.addWatcher(watcher2);
girl.addWatcher(watcher3);
//被观察者 通知观察者 状态改变
girl.notifyWatchers( "开心 爽");
//移除一个观察者
girl.removeWatcher(watcher2);
girl.notifyWatchers(" 不爽");
}
}