Observable和Observer

阅读更多

Observable和Observer

前一段时间看了一下Observable和Observer的事件框架,觉的还不错,先记下来
 
Observer接口和Observable类可用于Model-View模式中:当Model中的数据发生变化时,Model主动通知View此变化。
其中Model用Observable类来实现,而View可以用实现了Observer接口的类来实现。举例如下
 

import java.util.Observable;
import java.util.Observer;

/**
* @author
* 观察员

*/
public class Human implements Observer {

private String name;


public Human() {
super();
}

public Human(String name) {
super();

this.name = name;
}


public void update(Observable o, Object arg) {

//获取被观察对象当前的状态
System.out.println(((InvalidMan)o).getState());

//向当前观察者通知消息
System.out.println(name + arg);
}

}


import java.util.Observable;

/**
* 被观察者
**/
public class InvalidMan extends Observable {

private int state;

//差
public final static int STATE_BAD = 0;

//死
public final static int STATE_DEAD = -1;

//良好
public final static int STATE_FINE = 1;


public InvalidMan() {
super();
}

public InvalidMan(int state) {
this.state = state;
}


public int getState() {
return state;
}

public void setState(int state) {
this.state = state;
}

public void changeState(int state){
if(this.state != state)
{
this.state = state;
this.setChanged();

if(STATE_BAD == state || STATE_DEAD == state)
{
this.notifyObservers("...危险...");
}
else if(STATE_FINE == state)
{
this.notifyObservers("...准备出院...");
}
}
else
{
this.notifyObservers("...老样子...");
}
}
}

 

测试DEMO

import java.util.Observer;

public class ObserverDemo
{
public ObserverDemo()
{
}

public static void main(String[] args)
{
//被观察者
InvalidMan o1 = new InvalidMan(InvalidMan.STATE_BAD);
//观察员
Observer oo1 = new Human("医生");
//观察员
Observer oo2 = new Human("护士");
//观察员
Observer oo3 = new Human("家人");

//向被观察对象注册观察员
//为病人注册 观察员:医生,护士,家人
o1.addObserver(oo1);
o1.addObserver(oo2);
o1.addObserver(oo3);

//更改被观察对象的状态
o1.changeState(InvalidMan.STATE_DEAD);
o1.changeState(InvalidMan.STATE_BAD);
o1.changeState(InvalidMan.STATE_FINE);
}

}

你可能感兴趣的:(框架)