设计模式——观察者模式(附代码示例)

  • Post author:
  • Post category:其他


一. 传统方式

以天气预报以公告形式发送给第三方为例

1. 代码示例

CurrentConditions类,显示当前天气情况

public class CurrentConditions {
    private float temperature;
    private float pressure;
    private float humidity;

    //更新,第三方调用,推送
    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("今天的气温 " + temperature);
        System.out.println("今天的气压 " + pressure);
        System.out.println("今天的湿度 " + humidity);
    }
}

WeatherData类,含有CurrentConditions对象;当数据更新时就调用update方法

public class WeatherData {
    private float temperature;
    private float pressure;
    private float humidity;
    private CurrentConditions currentConditions;

    public WeatherData(CurrentConditions currentConditions) {
        this.currentConditions = currentConditions;
    }

    public float getTemperature() {
        return temperature;
    }


    public float getPressure() {
        return pressure;
    }


    public float getHumidity() {
        return humidity;
    }


    public void dataChange(){
        currentConditions.update(getTemperature(),getPressure(),getHumidity());
    }
    //当数据有更新时调用
    public void setData(float temperature,float pressure,float humidity){
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        //将最新的信息推送给第三方
        dataChange();
    }
}

Client类,客户端

public class Client {
    public static void main(String[] args) {
        CurrentConditions currentConditions = new CurrentConditions();
        WeatherData weatherData = new WeatherData(currentConditions);

        weatherData.setData(32,150,40);
        System.out.println("=====天气情况变化=====");
        weatherData.setData(34,155,44);
    }
}

2. 传统方式问题分析

在WeatherData中,当增加一个第三方,就需要创建一个对应的第三方的公告板对象,并加入到dataChange, 不利于维护,也不是动态加入,违反了ocp原则。

故引出观察者模式。


二. 观察者模式


1. 概念


观察者模式,对象之间多对一依赖的一种设计方案,被依赖的对象为Subject,依赖的对象为Observer, Subject通知Observer变化,

比如气象站是Subject, 是1的一方;第三方是Observer, 是多的一方。




Subject: 登记注册、移除和通知


registerObserver:

注册


removeObserver:

移除


notifyObservers:

通知所有的注册的用户,根据不同需求,可以是更新数据,让用户来取,也可能是实施推送,看具体需求定


Observer:接收输入


2. 代码示例


类图

Observer接口,抽象的观察者

public interface Observer {
    public void update(float temperature, float pressure, float humidity);
}

Subject接口,抽象定义登记注册、移除和通知

public interface Subject {
    public void registerObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObserver();
}

WeatherData类,实现Subject接口,含有观察者集合,用ArrayList管理,当数据更新时就调用update方法

public class WeatherData implements Subject{
    private float temperature;
    private float pressure;
    private float humidity;
    private ArrayList<Observer> observers;

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

    public float getTemperature() {
        return temperature;
    }


    public float getPressure() {
        return pressure;
    }


    public float getHumidity() {
        return humidity;
    }


    public void dataChange(){
        notifyObserver();
    }
    //当数据有更新时调用
    public void setData(float temperature,float pressure,float humidity){
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        //将最新的信息推送给第三方
        dataChange();
    }
    //注册一个观察者
    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }
    //移除一个观察者
    @Override
    public void removeObserver(Observer o) {
        if(observers.contains(o)) {
            observers.remove(o);
        }
    }

    @Override
    public void notifyObserver() {
        for (int i = 0; i < observers.size(); i++) {
            observers.get(i).update(this.temperature,this.pressure,this.humidity);
        }
    }
}

CurrentConditions类,实现Observer接口,显示当前天气情况

public class CurrentConditions implements Observer{
    private float temperature;
    private float pressure;
    private float humidity;

    //更新,第三方调用,推送
    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("***********气象台************");
        System.out.println("今天的气温 " + temperature);
        System.out.println("今天的气压 " + pressure);
        System.out.println("今天的湿度 " + humidity);
    }
}

3. 与传统方式对比

观察者模式设计后,会以集合的方式来管理用户(Observer), 包括注册,移除和通知。当增加观察者时,就不需要去修改核心类WeatherData,遵守了ocp原则。如下,新增BD第三方

public class BD implements Observer{
    private float temperature;
    private float pressure;
    private float humidity;

    //更新,第三方调用,推送
    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("***********百度************");
        System.out.println("百度的气温 " + temperature);
        System.out.println("百度的气压 " + pressure);
        System.out.println("百度的湿度 " + humidity);
    }
}

Client类

public class Client {
    public static void main(String[] args) {
        WeatherData weatherData = new WeatherData();

        CurrentConditions currentConditions = new CurrentConditions();
        weatherData.registerObserver(currentConditions);

        System.out.println("通过各个注册的观察者");
        weatherData.setData(26,140,30);
        System.out.println("======================================");
        System.out.println("新增百度第三方观察者,通过各个注册的观察者");
        BD bd = new BD();
        weatherData.registerObserver(bd);
        weatherData.setData(26,140,30);
    }
}



版权声明:本文为weixin_43899792原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。