观察者模式

[关键字]:java,design pattern,设计模式,《Java与模式》学习,阎宏,Ph.D,Factory,观察者模式,observer,event,java自定义事件,java事件机制,事件模型,事件监听,订阅发布,事件消息
[环境]:StarUML5.0 + JDK6
[作者]:天堂露珠 ( [email protected])
[正文]:
Overview    
package pattern.observer;
import java.util.Observer;
import java.util.Observable;
/**
* 观察者(Observer)模式:
* 使用Java类库支持的观察者模式
* java.util.Observer
* java.util.Observable
运行结果:
Prievious:,Changed:abc
Prievious:abc,Changed:abcd
Prievious:abcd,Changed:f
* @version 2009-5-6
* @author Winty([email protected])
*/
public class ObserverTest{
    public static void main(String[] args){
        Watched watched = new Watched();
        Watcher watcher = new Watcher();
        watched.addObserver(watcher);
        watched.changeData("abc");
        watched.changeData("abcd");
        watched.changeData("abcd");
        watched.changeData("f");
        watched.changeData(null);
        watched.changeData(null);
    }
}
/**
*具体被观察者,Observable是抽象被观察者
*/
class Watched extends Observable{
    private String data;
    public Watched(){
        data = "";
    }
    public String retrieveData(){
        return data;
    }
    public void changeData(String data){
        if(data!=null && !this.data.equals(data)){
            String dt = this.data;//记录变化前的数据
            this.data = data;
            setChanged();
            notifyObservers(dt);
        }       
    }
}
/**
*具体观察者,抽象观察者为Observer
*/
class Watcher implements Observer{
    @Override
    public void update(Observable o , Object arg){
        Watched wathed = (Watched)o;
        String previousData = (String)arg;
        System.out.print("Prievious:" + previousData + ",");
        System.out.println("Changed:" + wathed.retrieveData());
    }
}

[附件]:
pattern_Observable.zip

你可能感兴趣的:(模式,职场,休闲,观察)