乐趣区

关于设计模式:设计模式观察者模式

// 观察者
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.notifyObserver();
        weatherData.removeObserver(currentConditionsDisplay);
        weatherData.notifyObserver();}
}

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

退出移动版