设计模式之观察者模式

设计模式Java大约 2390 字

作用

定义对象间一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知自动更新。

原理

observer.png

Register:登记注册、移除和通知。

  • registerObserver:注册
  • removeObserver:移除
  • notifyObserver:通知所有的注册用户,根据不同需求,可以是更新数据,让用户来取,也可能是实施推送。

Observer:接收输入。

案例

Register

public interface Register {

    void registerObserver(Observer observer);

    void removeObserver(Observer observer);

    void notifyObservers();

}

ConcreteRegister

public class WeatherData implements Register {

    private float temperature;
    private float pressure;
    private float humidity;

    private List<Observer> observers;

    public WeatherData() {
        this.observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        observers.forEach(observer -> observer.update(temperature, pressure, humidity));
    }

    private void dataChange() {
        notifyObservers();
    }

    public void setData(float temperature, float pressure, float humidity) {
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        dataChange();
    }
}

Observer

public interface Observer {

    void update(float temperature, float pressure, float humidity);

}

ConcreteObserver

public class BaiduSite implements Observer {

    private float temperature;
    private float pressure;
    private float humidity;

    @Override
    public void update(float temperature, float pressure, float humidity) {
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        display();
    }

    public void display() {
        System.out.println("Baidu: " + temperature + " " + pressure + " " + humidity);
    }
}

调用

public class Client {
    public static void main(String[] args) {
        WeatherData weatherData = new WeatherData();
        BaiduSite baiduSite = new BaiduSite();
        weatherData.registerObserver(baiduSite);
        weatherData.setData(20, 100, 30);
        weatherData.removeObserver(baiduSite);
        weatherData.setData(10, 50, 15);
    }
}

源码

java.util.Observable:等价于Register,但Observable是类,已经实现了addObserverdeleteObservernotifyObservers方法。

java.util.Observer:等价于Observer,有update方法。

阅读 285 · 发布于 2019-12-30

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批