学习笔记:设计模式之观察者模式

天气预报项目需求,具体要求如下:
① 气象站可以将每天测量到的温度,湿度,气压等等以公告的形式发布出去(比如发布到自己的网站或第三方)
② 需要设计开放型API,便于其他第三方也能接入气象站获取数据
③ 提供温度、气压和湿度的接口
④ 测量数据更新时,要能实时的通知给第三方

观察者模式

思路分析图解:
观察者模式的好处

① 观察者模式设计后,会以集合的方式来管理用户(Observer),包括注册,移除和通知。
② 这样,我们增加观察者(这里可以理解成一个新的公告板),就不需要去修改核心类Weather不会修改代码,遵守了ocp原则。

代码是实现
public interface Subject {
    public void registObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObservers();
}
public class Weather implements Subject{
    private float temperature;
    private float pressure;
    private float humidity;
    private List observers;
    public Weather() {
        observers = new ArrayList();
    }
    public float getTemperature() {
        return temperature;
    }
    public void setTemperature(float temperature) {
        this.temperature = temperature;
    }
    public float getPressure() {
        return pressure;
    }
    public void setPressure(float pressure) {
        this.pressure = pressure;
    }
    public float getHumidity() {
        return humidity;
    }
    public void setHumidity(float humidity) {
        this.humidity = humidity;
    }
    public void setData(float temperature, float pressure, float humidity) {
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        notifyObservers();
    }
    @Override
    public void registObserver(Observer o) {
        observers.add(o);
    }
    @Override
    public void removeObserver(Observer o) {
        observers.remove(o);
    }
    @Override
    public void notifyObservers() {
        for(Observer o : observers) {
            o.update(getTemperature(), getPressure(), getHumidity());
        }
    }
}
public interface Observer {
    public void update(float temperature, float pressure, float humidity);
}
public class CurrentCondition 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("==========本站数据============");
        System.out.println("今天的天气为:" + temperature);
        System.out.println("今天的气压为:" + pressure);
        System.out.println("今天的湿度为:" + humidity);
    }
}
public class Test {
    public static void main(String[] args) {
        Weather weather = new Weather();
        CurrentCondition condition = new CurrentCondition();
        weather.registObserver(condition);
        weather.setData(25.2f, 70.2f, 60.7f);
    }
}

你可能感兴趣的:(学习笔记:设计模式之观察者模式)