【设计模式】JAVA Design Patterns——Observer(观察者模式)

2024-06-08 1120阅读

🔍目的


定义一种一对多的对象依赖关系这样当一个对象改变状态时,所有依赖它的对象都将自动通知或更新。

🔍解释


真实世界例子

在遥远的土地上生活着霍比特人和兽人的种族。他们都是户外生活的人所以他们密切关注天气的变化。可以说他们不断地关注着天气。

通俗描述

注册成为一个观察者以接收对象状态的改变。

维基百科

观察者模式是这样的一种软件设计模式:它有一个被称为主题的对象,维护着一个所有依赖于它的依赖者清单,也就是观察者清单,当主题的状态发生改变时,主题通常会调用观察者的方法来自动通知观察者们。

编程示例

首先创建天气观察者的接口以及我们的种族,兽人和霍比特人。

public interface WeatherObserver {
  void update(WeatherType currentWeather);
}
@Slf4j
public class Orcs implements WeatherObserver {
  @Override
  public void update(WeatherType currentWeather) {
    LOGGER.info("The orcs are facing " + currentWeather.getDescription() + " weather now");
  }
}
@Slf4j
public class Hobbits implements WeatherObserver {
  @Override
  public void update(WeatherType currentWeather) {
    switch (currentWeather) {
      LOGGER.info("The hobbits are facing " + currentWeather.getDescription() + " weather now");
  }
}

创建一个动态变化的天气:

@Slf4j
public class Weather {
  private WeatherType currentWeather;
  private final List 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);
  }
  /**
   * Makes time pass for weather.
   */
  public void timePasses() {
    var enumValues = WeatherType.values();
    currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
    LOGGER.info("The weather changed to {}.", currentWeather);
    notifyObservers();
  }
  private void notifyObservers() {
    for (var obs : observers) {
      obs.update(currentWeather);
    }
  }
}

执行示例:

    var weather = new Weather();
    weather.addObserver(new Orcs());
    weather.addObserver(new Hobbits());
    weather.timePasses();
    // The weather changed to rainy.
    // The orcs are facing rainy weather now
    // The hobbits are facing rainy weather now
    weather.timePasses();
    // The weather changed to windy.
    // The orcs are facing windy weather now
    // The hobbits are facing windy weather now
    weather.timePasses();
    // The weather changed to cold.
    // The orcs are facing cold weather now
    // The hobbits are facing cold weather now
    weather.timePasses();
    // The weather changed to sunny.
    // The orcs are facing sunny weather now
    // The hobbits are facing sunny weather now

🔍类图


【设计模式】JAVA Design Patterns——Observer(观察者模式)

🔍扩展延伸 

观察者模式在kafka client consumer中的使用:

大致逻辑:

consumer想要消费kafka broker中的数据需要发送request,request发送的结果用RequestFuture来表示,RequestFuture中包含RequestFutureListener,当request处理完成后RequestFutureListener的相关方法会被调用。RequestFutureCompletionHandler用来处理RequestFuture、ClientResponse还有RuntimeException。

依赖关系:

RequestFutureListener为观察者,onSuccess和onFail方法相当于之前的update方法;RequestFuture为被观察者,addListener相当于attach方法,fireSuccess和fireFailure方法相当于notify方法。

RequestFutureListener部分代码:
public interface RequestFutureListener {
    void onSuccess(T value);
    void onFailure(RuntimeException e);
}
RequestFuture部分代码: 
public class RequestFuture implements ConsumerNetworkClient.PollCondition {
    private static final Object INCOMPLETE_SENTINEL = new Object();
    private final AtomicReference result = new AtomicReference(INCOMPLETE_SENTINEL);
    private final ConcurrentLinkedQueue listeners = new ConcurrentLinkedQueue();
    private final CountDownLatch completedLatch = new CountDownLatch(1);
    public void complete(T value) {
        try {
            if (value instanceof RuntimeException)
                throw new IllegalArgumentException("The argument to complete can not be an instance of RuntimeException");
            if (!result.compareAndSet(INCOMPLETE_SENTINEL, value))
                throw new IllegalStateException("Invalid attempt to complete a request future which is already complete");
            fireSuccess();
        } finally {
            completedLatch.countDown();
        }
    }
//遍历listener并调用其success时的方法
    private void fireSuccess() {
        T value = value();
        while (true) {
            RequestFutureListener listener = listeners.poll();
            if (listener == null)
                break;
            listener.onSuccess(value);
        }
    }
//遍历listener并调用其fail时的方法
    private void fireFailure() {
        RuntimeException exception = exception();
        while (true) {
            RequestFutureListener listener = listeners.poll();
            if (listener == null)
                break;
            listener.onFailure(exception);
        }
    }
    //增加listener
    public void addListener(RequestFutureListener listener) {
        this.listeners.add(listener);
        if (failed())
            fireFailure();
        else if (succeeded())
            fireSuccess();
    }

🔍适用场景


在下面任何一种情况下都可以使用观察者模式

  • 当抽象具有两个方面时,一个方面依赖于另一个方面。将这些方面封装在单独的对象中,可以使你分别进行更改和重用
  • 当一个对象的改变的同时需要改变其他对象,同时你又不知道有多少对象需要改变时
  • 当一个对象可以通知其他对象而无需假设这些对象是谁时。换句话说,你不想让这些对象紧耦合。

    🔍Ending


    观察者模式(Observer Pattern)是一种行为设计模式,它定义了一种一对多的依赖关系,使得当一个对象的状态发生变化时,所有依赖于它的对象都会得到通知并自动更新。

    在观察者模式中,通常包含以下几个角色:

    1. 主题(Subject):被观察的对象,它会维护一组观察者对象,并在自身状态发生变化时通知观察者。
    2. 观察者(Observer):观察主题对象的状态变化,并根据变化做出相应的动作。
    3. 具体主题(ConcreteSubject):实现了主题接口的具体对象,负责维护观察者列表,并在自身状态发生变化时通知观察者。
    4. 具体观察者(ConcreteObserver):实现了观察者接口的具体对象,负责接收主题对象的通知,并根据通知更新自身状态。

    希望本文能够帮助读者更深入地理解观察者模式,并在实际项目中发挥其优势。谢谢阅读!


    希望这份博客草稿能够帮助到你。如果有其他需要修改或添加的地方,请随时告诉我。

    【设计模式】JAVA Design Patterns——Observer(观察者模式)

VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]