package com.defonds.buffer; public interface Subject { public void registerObserver(Observer observer); public void removeObserver(Observer observer); public void notifyObservers(); }
package com.defonds.buffer; public interface Observer { public void update(int onlineNum); }
package com.defonds.buffer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class BufferData implements Subject { private int onlinePlayersNum = 0; // store online players num private List<Observer> observers = new ArrayList<Observer>(); // refer to all observers @Override public void registerObserver(Observer observer) { this.observers.add(observer); // add one observer } @Override public void removeObserver(Observer observer) { int i = this.observers.indexOf(observer); if (i >= 0) { this.observers.remove(i); } } @Override public void notifyObservers() { Iterator<Observer> iterator = this.observers.iterator(); while (iterator.hasNext()) { iterator.next().update(this.onlinePlayersNum); } } public void setOnlinePlayersNum(int onlinePlayersNum) { this.onlinePlayersNum = onlinePlayersNum; this.notifyObservers(); } }
package com.defonds.buffer; public class PublicDisplay extends Thread implements Observer, Display { private int onlineNum; private boolean changed = false; @Override public void update(int onlineNum) { this.onlineNum = onlineNum; this.changed = true; } @Override public void display() { System.out.println("The current number of players online is : " + this.onlineNum); } @Override public void run() { while (this.changed) { this.display(); this.changed = false; } } }
《设计模式:可复用面向对象软件的基础》观察者模式中的 ConcreteObserver 角色之二,在本文中是为 InternalDisplay 类,源码:
package com.defonds.buffer; public class InternalDisplay extends Thread implements Observer, Display { private int oldNum = 0; private int onlineNum = 0; private boolean changed = false; @Override public void update(int onlineNum) { this.oldNum = this.onlineNum; this.onlineNum = onlineNum; this.changed = true; } @Override public void display() { System.out.println("The current number of players online is : " + this.onlineNum); if(this.onlineNum > this.oldNum) { System.out.println("The number of online upward"); } else { System.out.println("The number of online decline"); } } @Override public void run() { while (this.changed) { this.display(); this.changed = false; } } }