Observer(观察者)模式从名称也可以看出该设计模式的使用意义。当用户想让某一事物或者行为在改变时能够主动修改其他某些事物或者行为时,就需要观察者模式。观察者模式分为两种对象:观察对象和依赖观察者,当观察对象改变时,其依赖观察者也会做相应的改变。观察者设计模式应用在许多地方,比如Android中实现有信息插入数据库的时候动态修改短信列表,就需要短信软件观察Android短信数据库,达到实时同步。
由于java内部实现了观察者模式,我们只需要在其基础上进行业务逻辑处理即可。
举个警察监控小偷的例子,如果小偷有动静,警察也会做相应的动静。小偷睡觉,警察就睡觉;小偷走路,警察就会跟随;小偷偷东西,警察就把他抓了。
小偷实现:
public class Thief extends Observable{
public void sleep() {
System.out.println("thief issleeping now");
setChanged();
notifyObservers("sleep");
}
public void walk() {
System.out.println("thief iswalking now");
setChanged();
notifyObservers("walk");
}
public void steal() {
System.out.println("good nightfor stealing");
setChanged();
notifyObservers("steal");
}
}
警察实现:
public class Police implements Observer {
private static int count = 0;
private int index = ++count;
@Override
public void update(Observable thief, Object actor) {
if(actor.equals("sleep")) {
System.out.println("police" + index + " issleeping");
} else if(actor.equals("walk")) {
System.out.println("police" + index + " istracking");
} else if(actor.equals("steal")) {
System.out.println("police" + index + " catch thethief");
}
}
}
测试代码:
public static void main(String[] args) {
Thief thief = new Thief();
Police p1 = new Police();
Police p2 = new Police();
thief.addObserver(p1);
thief.addObserver(p2);
thief.sleep();
thief.walk();
thief.steal();
}
打印结果如下:
thief is sleeping now
police 2 is sleeping
police 1 is sleeping
thief is walking now
police 2 is tracking
police 1 is tracking
good night for stealing
police 2 catch the thief
police 1 catch the thief