观察者(Observer)模式 测试

Head Frist定义:

观察者模式定义的对象之间的一对多依赖,这样一来,当一个对象改变状态时,
它的所有依赖者都会收到通知

观察者(Observer)模式 测试_第1张图片

ISubjector接口

public interface ISubjector {
    public void rigistObserver(IObserver o );
    public void removeObserver(IObserver o );
    public void notifiyObservers();
}

WeatherData类实现ISubjector接口

public class WeatherData implements ISubjector {
    private int temp;// 温度  
    private int humidity;// 湿度
    private int pressure;// 压强
    private ArrayList observers;
    public WeatherData() {
        observers = new ArrayList<>();
    }
    @Override
    public void rigistObserver(IObserver o) {
        observers.add(o);
    }
    @Override
    public void removeObserver(IObserver o) {
        int index = observers.indexOf(o);
        if(index >= 0) {
            observers.remove(index);
        }
    }
    @Override
    public void notifiyObservers() {
        for (int i = 0; i < observers.size(); i++) {
            IObserver observer = (IObserver) observers.get(i);
            observer.update(getTemp(), getHumidity(), getPressure());
        }
    }

//  当数据改变时执行
    public void dataChanged() {
        notifiyObservers();
    }
//  数据改变
    public void setDatas(int temp,int humidity,int pressure){
        this.temp = temp;
        this.humidity = humidity;
        this.pressure = pressure;
        dataChanged();
    }
    public int getTemp() {
        return temp;
    }
    public int getHumidity() {
        return humidity;
    }
    public int getPressure() {
        return pressure;
    }


}

IObserver接口

public interface IObserver {
    public void update(int temp,int humidity,int pressure);
}

CurrentConditionsDisplay类实现IObserver

public class CurrentConditionsDisplay implements  IObserver {

    private int temp;
    private int humidity;
    private int pressure;
    @Override
    public void update(int temp, int humidity, int pressure) {
        this.temp = temp;
        this.humidity = humidity;
        this.pressure = pressure;
        display();
    }
    public void display() {
        System.out.println("-----------------");
        System.out.println("实时温度:"+temp);
        System.out.println("实时湿度:"+humidity);
        System.out.println("实时气压"+pressure);
    }

}

测试代码

WeatherData weatherStation = new WeatherData();
        CurrentConditionsDisplay condition = new CurrentConditionsDisplay();
        weatherStation.rigistObserver(condition);
        weatherStation.setDatas(20, 65, 30);
        weatherStation.setDatas(23, 75, 40);
        weatherStation.setDatas(28, 85, 50);

运行结果

-----------------
实时温度:20
实时湿度:65
实时气压30
-----------------
实时温度:23
实时湿度:75
实时气压40
-----------------
实时温度:28
实时湿度:85
实时气压50

当weatherData 的数据改变时,weatherData的观察者门都会得到通知,从而做出一些动作

你可能感兴趣的:(java,设计模式)