首页 > 其他 > 详细

设计模式--观察者模式

时间:2019-10-14 22:14:15      阅读:83      评论:0      收藏:0      [点我收藏+]

拉模式的观察者

主题Subject接口

public interface Subject {
  public void registerObesrver(Observer observer);

  public void removeObeserver(Observer observer);

  public void notifyObeservers();
}

天气数据

public class WeatherData implements Subject {
  private Double temperate = null;

  // ArrayList默认容量为10,当大量添加observers,可能存在性能问题
  private List<Observer> observers = new ArrayList<>();

  public Double getTemperate() {
    return temperate;
  }

  public void setTemperate(Double temperate) {
    this.temperate = temperate;
    notifyObeservers();
  }

  @Override
  public void registerObesrver(Observer observer) {
    observers.add(observer);
  }

  @Override
  public void removeObeserver(Observer observer) {
    observers.remove(observer);
  }

  @Override
  public void notifyObeservers() {
    for (Observer observer : observers) {
      observer.update();
    }
  }


}

观察者Observer

public interface Observer {
  public void update();
}

tv观察者

public class TvOberser implements Observer {

  private WeatherData weatherData;

  public TvOberser(WeatherData weatherData) {
    this.weatherData = weatherData;
    weatherData.registerObesrver(this);
  }

  @Override
  public void update() {
    System.out.println("**************************");
    System.out.println("*********  TV  ***********");
    System.out.println("temperate:" + weatherData.getTemperate());
    System.out.println("**************************");

  }
}

Radio观察者

public class RadioObserver implements Observer {

  public WeatherData weatherData;

  public RadioObserver(WeatherData weatherData) {
    this.weatherData = weatherData;
    weatherData.registerObesrver(this);
  }

  @Override
  public void update() {
    System.out.println("-----------------------------");
    System.out.println("---------  Radio  -----------");
    System.out.println("temperate:" + weatherData.getTemperate());
    System.out.println("-----------------------------");
  }
}

测试类

public class Main {
  public static void main(String args[]) {
    WeatherData weatherData = new WeatherData();
    TvOberser tvOberser = new TvOberser(weatherData);
    RadioObserver radioObserver = new RadioObserver(weatherData);
    weatherData.setTemperate(100.0);
    weatherData.setTemperate(99.0);
    weatherData.setTemperate(98.0);
    weatherData.setTemperate(96.0);
  }
}

 推模式后续更新----------

设计模式--观察者模式

原文:https://www.cnblogs.com/lz-0011/p/11674513.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!