Head First Design Patterns - Observer Pattern

The Observer Pattern defines a one-to-many dependency between objects so that when one

object changes state, all of its dependents are notified and updated automatically.

The Observer Pattern defines a one-to-many relatioship between objects.

Design Principle

  • Strive for loosely coupled designs between objects that interact

public interface Subject{

  public void registerObserver(Observer o);

  public void removeObserver(Observer o);

  public void notifyObservers();

}

public interface Observer{

  public void update(float temp, float humidity, float pressure);

}

public interface DisplayElement{

  public void display();

}

public class WeatherData implements Subject{

  private ArrayList observers;

  private float temperature;

  private float humidity;

  private float pressure;

  public WeatherData(){

  observers = new ArrayList();

  }

  public void registerObserver(Observer o){

    observers.add(o);

  }

  public void removeObserver(Observer o){

    int i = observers.indexOf(o);

    if(i>=0){

      observers.remove(i);

    }

  }

  public void notifyObservers(){

    for(int i = 0;i<observers.size();i++){

      Observer observer = (Observer)observers.get(i);

      observer.update(temperature, humidity, pressure);

    }

  }

  public void measurementsChanged(){

    notifyObservers();

  }

  public void setMeasurements(float temperature, float humidity, float pressure){

    this.temperature = temperature;

    this.humidity = humidity;

    this.pressure = pressure;

    measurementsChanged();

  }

}

public class CurrentConditionsDisplay implements Observer, DisplayElement{

  private float temperature;

  private float humidity;

  private Subject weatherData;

  public CurrentConditionsDisplay(Subject weatherData){

    this.weatherData = weatherData;

    weatherData.registerObserver(this);

  }

  public void update(float temperature, float humidity, float pressure){

    this.temperature = temperature;

    this.humidity = humidity;

    display();

  }

  public void display(){

    //do something

  }

}

转载于:https://www.cnblogs.com/zhuqiang/archive/2012/04/25/2469515.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值