学习Head First设计模式Day2 - 简书

96
妙蛙种子爱吃蒜
2017.05.02 11:54* 字数 67

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> observers;
private float date1;
private float date2;
private float date3;

    public  WeatherDate() {
        observers=new ArrayList<Observers>();
    }
    @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<observers.size();i++){
            Observers observer=(Observers)observers.get(i);
            observer.update(date1, date2, date3);
        }
    }
    public void measurementChange(){
        notifyObserver();
    }
    public void setMeasurements(float date1,float date2,float date3){
        this.date1=date1;
        this.date2=date2;
        this.date3=date3;
        measurementChange();
    }

    public float getDate1() {
        return date1;
    }

    public void setDate1(float date1) {
        this.date1 = date1;
    }

    public float getDate2() {
        return date2;
    }

    public void setDate2(float date2) {
        this.date2 = date2;
    }

    public float getDate3() {
        return date3;
    }

    public void setDate3(float date3) {
        this.date3 = date3;
    }
    

}

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设计模式
Web note ad 1