观察者模式

2016-10-21  本文已影响0人  狐尼克朱迪

定义

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

使用场景

例子

一个简单的天气预报的例子:

public interface WeatherObserver {
  void update(WeatherType currentWeather);
}

public enum WeatherType {
  SUNNY, RAINY, WINDY, COLD;
  @Override
  public String toString() {
    return this.name().toLowerCase();
  }
}

// 发布者
public class Weather {
  private WeatherType currentWeather;
  private List<WeatherObserver> observers;

  public Weather() {
    observers = new ArrayList<>();
    currentWeather = WeatherType.SUNNY;
  }

  public void addObserver(WeatherObserver obs) {
    observers.add(obs);
  }

  public void removeObserver(WeatherObserver obs) {
    observers.remove(obs);
  }

  public void timePasses() {
    WeatherType[] enumValues = WeatherType.values();
    currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
    System.out.println("The weather changed to " + currentWeather + ".");
    notifyObservers();
  }

  private void notifyObservers() {
    for (WeatherObserver obs : observers) {
      obs.update(currentWeather);
    }
  }
}


// 两个观察者
public class Hobbits implements WeatherObserver {

  @Override
  public void update(WeatherType currentWeather) {
    switch (currentWeather) {
      case COLD:
        System.out.println("The hobbits are shivering in the cold weather.");
        break;
      case RAINY:
        System.out.println("The hobbits look for cover from the rain.");
        break;
      case SUNNY:
        System.out.println("The happy hobbits bade in the warm sun.");
        break;
      case WINDY:
        System.out.println("The hobbits hold their hats tightly in the windy weather.");
        break;
      default:
        break;
    }
  }
}

public class Orcs implements WeatherObserver {

  @Override
  public void update(WeatherType currentWeather) {
    switch (currentWeather) {
      case COLD:
        System.out.println("The orcs are freezing cold.");
        break;
      case RAINY:
        System.out.println("The orcs are dripping wet.");
        break;
      case SUNNY:
        System.out.println("The sun hurts the orcs' eyes.");
        break;
      case WINDY:
        System.out.println("The orc smell almost vanishes in the wind.");
        break;
      default:
        break;
    }
  }
}

// 测试
public class App {
  public static void main(String[] args) {

    Weather weather = new Weather();
    weather.addObserver(new Orcs());
    weather.addObserver(new Hobbits());

    weather.timePasses();
    weather.timePasses();
  }
}

分析

观察者模式体现了为了交互对象之间的松耦合设计而努力的设计原则!

参考

iluwatar/java-design-patterns

上一篇 下一篇

猜你喜欢

热点阅读