标签:
import java.util.ArrayList;
import java.util.List;
publicclassSubject{
privateList<Observer> observers
=newArrayList<Observer>();
privateint state;
publicint getState(){
return state;
}
publicvoid setState(int state){
this.state = state;
notifyAllObservers(state);
}
publicvoid attach(Observer observer){
observers.add(observer);
}
publicvoid notifyAllObservers(int state){
for(Observer observer : observers){
observer.update(int state);
}
}
}
public interface Observer{
/**
* 更新接口
* @param subject 传入主题对象,方便获取相应的主题对象的状态
*/
publicvoid update(Subject subject);
}
import java.util.Observable;
import java.util.Observer;
publicclassMainRoot{
publicstaticvoid main(String[] args){
Observer consumer =newConsumer();
MilkProvider provider =newMilkProvider();
provider.addObserver(consumer);
provider.milkProduced();
}
staticclassMilkProvider extends Observable{
publicvoid milkProduced(){
setChanged();//状态改变,必须调用
notifyObservers();
}
}
staticclassConsumer implements Observer{
@Override
publicvoid update(Observable arg0,Object arg1){
System.out.println("Consumer update..."+ arg0 +";arg1="+ arg1);
}
}
}
public interface Observer{
void update(Observable o,Object arg);
}
publicclassObservable{
private boolean changed =false;
privateVector obs;
publicObservable(){
obs =newVector();
}
// 将一个观察者添加到观察目标中
public synchronized void addObserver(Observer o){
if(o == null)
thrownewNullPointerException();
if(!obs.contains(o)){
obs.addElement(o);
}
}
//将一个观察者从观察目标中删除
public synchronized void deleteObserver(Observer o){
obs.removeElement(o);
}
publicvoid notifyObservers(){
notifyObservers(null);
}
/* 如果本对象有变化(hasChanged 方法返回true),调用本方法通知所有登记的观察者,
即调用它们的update()方法,传入this和arg作为参数 */
publicvoid notifyObservers(Object arg){
Object[] arrLocal;
synchronized (this){
if(!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for(int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
//将观察者聚集清空
public synchronized void deleteObservers(){
obs.removeAllElements();
}
//将“已变化”设置为true
protected synchronized void setChanged(){
changed =true;
}
//将“已变化”重置为false
protected synchronized void clearChanged(){
changed =false;
}
// 检测本对象是否已变化
public synchronized boolean hasChanged(){
return changed;
}
public synchronized int countObservers(){
return obs.size();
}
}
标签:
原文地址:http://www.cnblogs.com/Doing-what-I-love/p/5621157.html