当前头条:设计模式-观察者模式(二)


(资料图)

接下来,我们实现具体主题类ConcreteSubject和具体观察者类ConcreteObserver:

import java.util.ArrayList;import java.util.List;public class ConcreteSubject implements Subject {    private List observers;    private float temperature;    private float humidity;    private float pressure;    public ConcreteSubject() {        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() {        for (Observer observer : observers) {            observer.update(temperature, humidity, pressure);        }    }    public void setMeasurements(float temperature, float humidity, float pressure) {        this.temperature = temperature;        this.humidity = humidity;        this.pressure = pressure;        measurementsChanged();    }    public void measurementsChanged() {        notifyObservers();    }}public class ConcreteObserver implements Observer {    private float temperature;    private float humidity;    private float pressure;    @Override    public void update(float temperature, float humidity, float pressure) {        this.temperature = temperature;        this.humidity = humidity;        this.pressure = pressure;        display();    }    public void display() {        System.out.println("Current conditions: " + temperature                + "F degrees and " + humidity + "% humidity and " + pressure + "Pa");    }}
关键词:
图片版权归原作者所有,如有侵权请联系我们,我们立刻删除。
新化月报网报料热线:886 2395@qq.com

相关文章

你可能会喜欢

最近更新

推荐阅读