学习Head First设计模式Day2

Java设计模式之观察者模式

观察者模式: 定义了对象之间的一对多的依赖,这样一来,当一个对象改变状态时,他的所有依赖都会接到通知并自动更新

完整的想法

package observer_mode;

public interface Subject {
    public void registObserver(Observers o);
    public void removeOnserver(Observers o);
    public void notifyObserver();

}

package observer_mode;

public interface Observers {
    public void update(float date1,float date2,float date3);
}

package observer_mode;

import java.util.ArrayList;

public class WeatherDate implements Subject {
private ArrayList observers;
private float date1;
private float date2;
private float date3;

    public  WeatherDate() {
        observers=new ArrayList();
    }
    @Override
    public void registObserver(Observers o) {
        observers.add(o);
    }

    @Override
    public void removeOnserver(Observers o) {
        int i=observers.indexOf(o);
        if(i>0){
            observers.remove(i);
        }
    }

    @Override
    public void notifyObserver() {
        for(int i=0;i
package observer_mode;

public class Current implements Observers,Display {

    private float date1;
    private float date2;
    WeatherDate watherdate;
    public  Current(WeatherDate watherdate){
        this.watherdate=watherdate;
        watherdate.registObserver(this);
        }
    @Override
    public void display() {
        System.out.println(date1+"  "+date2);
    }

    @Override
    public void update(float date1, float date2, float date3) {
        this.date1=date1;
        this.date2=date2;
        display();
    }

}

package observer_mode;

public class WeatherStation {

    public static void main(String[] args) {
        WeatherDate weatherDate=new WeatherDate();
        Current current=new Current(weatherDate);
        weatherDate.setMeasurements(3.3f, 2.3f, 4.0f);
    }

}

你可能感兴趣的:(学习Head First设计模式Day2)