其他分享
首页 > 其他分享> > 观察者模式

观察者模式

作者:互联网

//观察者
public interface Observer {
    public void update(float temp, float humidity, float pressure);
}
//观察者行为
public interface Displayment {
    public void display();
}
//主题
public interface Subject {
    public void registerObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObserver();
}
//观察者1
public class CurrentConditionsDisplay implements Observer, Displayment{
    private float temp;
    private float humidity;
    private Subject weatherData;

    public void CurrentConditionsDisplay(Subject weatherData){
        this.weatherData = weatherData;
    }

    public void display() {
        System.out.println("Current conditions: " + temp + "F degrees and "+ humidity + " % humidity");
    }

    public void update(float temp, float humidity, float pressure) {
        this.temp = temp;
        this.humidity = humidity;
        display();
    }
}
//主题相关的实例
public class WeatherData implements Subject {
    private ArrayList observers;
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData(){
        this.observers = new ArrayList<Observer>();
    }
    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        observers.remove(o);
    }

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

    public void measurementsChanged(){
        notifyObserver();
    }

    public void setMeasurements(float temperature, float humidity, float pressure){
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
    }
}
//测试
public class WeatherDataTest extends TestCase {

    public void testRegisterObserver() {
        WeatherData weatherData = new WeatherData();
        weatherData.setMeasurements(23,15,175);
        CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay();
//        CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData);
        weatherData.registerObserver(currentConditionsDisplay);
        weatherData.measurementsChanged();
        weatherData.removeObserver(currentConditionsDisplay);
        weatherData.notifyObserver();
    }
}

//测试结果
Current conditions: 23.0F degrees and 15.0 % humidity

标签:Observer,weatherData,void,float,观察者,模式,humidity,public
来源: https://www.cnblogs.com/mtjb1dd/p/15740655.html