首页>聚焦 > 正文

设计模式-观察者模式(二)

2023-05-05 15:31:25来源:腾讯云


【资料图】

接下来,我们实现具体主题类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");    }}

标签:

责任编辑:

免责声明

头条新闻

精彩新闻

精彩要闻