[关键字]:java,design pattern,设计模式,《Java与模式》学习,阎宏,Ph.D,Factory,观察者模式,observer,event,java自定义事件,java事件机制,事件模型,事件监听,订阅发布,事件消息
[环境]:StarUML5.0 + JDK6
[作者]:天堂露珠 (wintys@gmail.com) http://www.blogjava.net/wintys/
[正文]:
ObserverTest.java:
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(wintys@gmail.com)
*/
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());
}
}
[附件]:
ObserverTest.java、Observer.java、Observable.java
原创作品,转载请注明出处。
作者:Winty (wintys@gmail.com)
博客:http://www.blogjava.net/wintys
posted on 2009-10-11 19:56
天堂露珠 阅读(1721)
评论(0) 编辑 收藏 所属分类:
Pattern