標籤:update main get port abs print not image 代碼
/** 抽象的觀察者 */public interface Watcher { // status 為 被被觀察著傳遞過來的狀態 public void update(String status);}
import java.util.LinkedList;/** 抽象的被觀察者 */public abstract class Watched { /** 用來儲存註冊的觀察者對象 */ protected LinkedList<Watcher> watcherList = new LinkedList<Watcher>(); /** 註冊觀察者對象 */ public abstract void add(Watcher watcher); /** 刪除觀察者對象 */ public abstract void remove(Watcher watcher); /** 通知所有註冊的觀察者對象 */ public abstract void notifyWatchers();}
// 具體的觀察者public class Boy implements Watcher { @Override public void update(String status) { System.out.println(this + " 監聽到狀態 " + status); }}
/** 具體的被觀察者: 添加和刪除方法最好加上同步 */public class Girl extends Watched { private String status; public void setStatus(String status) { this.status = status; } @Override public synchronized void add(Watcher watcher) { watcherList.add(watcher); } @Override public synchronized void remove(Watcher watcher) { watcherList.remove(watcher); } @Override public void notifyWatchers() { for (Watcher w : watcherList) { w.update(status); } }}
測試代碼與結果
public class Test { public static void main(String[] args) throws Exception { Girl girl = new Girl(); for (int i = 0; i < 3; i++) { girl.add(new Boy()); } girl.setStatus("happy"); girl.notifyWatchers(); TimeUnit.SECONDS.sleep(1); girl.setStatus("unhappy"); girl.notifyWatchers(); }}
參考:
http://www.cnblogs.com/mengdd/archive/2013/02/07/2908929.html
http://www.cnblogs.com/mengdd/archive/2013/02/07/2908929.html
java 觀察者模式