java 观察者模式


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 List<IWatcher> watchers = new ArrayList<IWatcher>();
@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”);
}
}



来源博客:Wang Jie's Blog
本文链接:https://blog.wangjiegulu.com/2012/11/20/java-观察者模式/
版权声明:本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处。