JAVA支持的观察者模式
JAVA支持的观察者模式,适用jdk自带的Observer、Observable
package com.wh.cms.webinfo.observer;
import java.util.Observable;
import java.util.Observer;
/**
* 观察者
* Created by zyb on 15/11/12.
*/
public class Watcher implements Observer {
public Watcher(Observable o) {
o.addObserver(this);
}
/**
* 接收所有被观察者消息
*
* @param o
* @param arg
*/
@Override
public void update(Observable o, Object arg) {
Object obj = o.getClass();
if (obj.equals(Watched.class)) {
System.out.println("Watched状态发生改变:" + ((Watched) o).getWatcherState());
} else if (obj.equals(Watched2.class)) {
System.out.println("Watched2状态发生改变:" + ((Watched2) o).getWatcherState());
}
}
}
package com.wh.cms.webinfo.observer;
import java.util.Observable;
/**
* 被观察者
* Created by zyb on 15/11/12.
*/
public class Watched extends Observable {
/**
* 观察者监听状态
*/
private String watcherState = "";
public String getWatcherState() {
return watcherState;
}
public void setWatcherState(String watcherState) {
if (!this.watcherState.equals(watcherState)) {
this.watcherState = watcherState;
setChanged();//更新状态
}
notifyObservers(); //更新提醒
}
}
package com.wh.cms.webinfo.observer;
import java.util.Observable;
/**
* 被观察者
* Created by zyb on 15/11/12.
*/
public class Watched2 extends Observable {
/**
* 观察者监听状态
*/
private String watcherState = "";
public String getWatcherState() {
return watcherState;
}
public void setWatcherState(String watcherState) {
if (!this.watcherState.equals(watcherState)) {
this.watcherState = watcherState;
setChanged();//更新状态
}
notifyObservers(); //更新提醒
}
}
package com.wh.cms.webinfo.observer;
import java.util.Observer;
/**
* Created by zyb on 15/11/12.
*/
public class Test {
public static void main(String[] args) {
//创建被观察者对象
Watched watched = new Watched();
Watched2 watched2 = new Watched2();
//创建观察者对象,并将被观察者对象登记
Observer watcher = new Watcher(watched);
Observer watcher2 = new Watcher(watched2);
//给被观察者状态赋值
watched.setWatcherState("start");
watched.setWatcherState("run");
watched.setWatcherState("stop");
watched.setWatcherState("hahaha");
watched2.setWatcherState("start");
watched2.setWatcherState("run");
watched2.setWatcherState("stop");
watched2.setWatcherState("hahaha");
}
}