电脑版

环球热推荐:设计模式-观察者模式(二)

2023-05-05 16:00:04来源:腾讯云


(资料图片仅供参考)

接下来,我们实现具体主题类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");    }}
本网推荐
相关新闻