观察者设计模式案例

package my.cn.pl.observer;


public interface ObserverImpl {

    public void upDdata(String temperature, String pressure, String humidity);
}

package my.cn.pl.observer;

public interface SubjectImpl {

public void registerData(ObserverImpl observer);


public void removeData(ObserverImpl observer);

public void notifyData();

}

package my.cn.pl.observer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 */
public class WeatherData implements SubjectImpl {
    protected List<ObserverImpl> list = new ArrayList<>();

    protected String mPressure;
    protected String mTemperature;
    protected String mHumidity;

    @Override

    public void registerData(ObserverImpl observer) {
        list.add(observer);

    }

    @Override
    public void removeData(ObserverImpl observer) {
        if (list.contains(observer)) {
            list.remove(observer);
        }

    }

    @Override
    public void notifyData() {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).upDdata(mTemperature, mPressure, mHumidity);
            }
        }
    }

    public void setWeatherData(String temperature, String pressure, String humidity) {
        this.mHumidity = humidity;
        this.mPressure = pressure;
        this.mTemperature = temperature;
        setNotifyChange();
    }

    public void setNotifyChange() {
        notifyData();
    }

}

package my.cn.pl.observer;

public abstract class AbstractBaseClient {
protected WeatherData mWeatherData;

public AbstractBaseClient(WeatherData data) {
    mWeatherData = data;
}

}

package my.cn.pl.observer;

import my.cn.pl.Utils.OutPrint;


public class ClientOne extends AbstractBaseClient implements ObserverImpl {


    public ClientOne(WeatherData data) {
        super(data);
        mWeatherData.registerData(this);
    }

    @Override
    public void upDdata(String temperature, String pressure, String humidity) {
        OutPrint.outPrint("clientone", temperature, pressure, humidity);
    }


}

package my.cn.pl.observer;

import my.cn.pl.Utils.OutPrint;

public class ClientTwo extends AbstractBaseClient implements ObserverImpl {

public ClientTwo(WeatherData data) {
    super(data);
    mWeatherData.registerData(this);
}

@Override
public void upDdata(String temperature, String pressure, String humidity) {
    OutPrint.outPrint("ClientTwo", temperature, pressure, humidity);
}

}

package my.cn.pl.observer;

import my.cn.pl.observer.ClientOne;
import my.cn.pl.observer.WeatherData;


public class WeatherTest {

    public void main() {
        WeatherData data = new WeatherData();
        ClientOne clientOne = new ClientOne(data);
        ClientTwo two = new ClientTwo(data);
        data.removeData(clientOne);
        data.setWeatherData("温度", "压力", "湿度");

    }

}