一、什么是观察者模式

定义对象间的一种一对多的依赖关系,当一个对象(被观察者Observable)的状态发生改变时,依赖于它的对象(Observer)都得到通知并且被自动更新。

被观察者(Observable)的核心方法:

setChange();//告知数据改变
    notifyObservers();//给观察者发送信号

观察者(Observer)的核心方法:

update(Observable observable, Object o);//观察者接到信号后更新

二、为什么要使用观察者模式

优点:

1、关联行为,并且行为可拆分,而不是组合关系
2、解除耦合,使得各自的变换都不会影响另一边的变换

缺点:

需要考虑开发效率和运行效率的问题,java中的消息通知一般是顺序执行,如果一个观察者卡顿(比如陷入死循环),会产生如下效果:

while(1){
    // 死循环懵逼.jpg
    }

这时候需要注意判断需求是否需要异步实现。

三、以天气-气象站为例的简单观察者模式(使用Observable和Observer)

作为被观察者的天气:

public class Weather extends Observable {

    private String description;

    public Weather(String des){
        this.description = des;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
        setChanged();
        notifyObservers();
    }

    @Override
    protected synchronized void setChanged() {
        super.setChanged();
        Log.d("Observable","Weather发生了改变:"+description);
    }

    @Override
    public void notifyObservers() {
        super.notifyObservers();
        Log.d("Observable", "notifyObservers: "+"已经通知了气象站");
    }
}

作为观察者的气象站:

public class Station implements Observer {

        private static String TAG = "Observer";
        private MainActivity activity;

        public Station(MainActivity activity,Weather weather){
        this.activity = activity;
        }

        @Override
        public void update(Observable observable, Object o) {
            Log.d(TAG, "update");
             if (observable instanceof Weather){
                Weather weather2 = (Weather) observable;
                activity.Change(weather2.getDescription());
            }
         }
}

使用:

private Weather weather = new Weather("");  //被观察者
    private Station station = new Station(MainActivity.this);//观察者
    weather.addObserver(station);//划重点!!

然后就可以愉快的使用观察者模式了,当然,这只是最最最最简单的观察者模式,在实际情况中,我们会用到更复杂的写法。