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

🔍目的


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

🔍解释


真实世界例子

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

通俗描述

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

维基百科

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

编程示例

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

java 复制代码
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");
  }
}

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

java 复制代码
@Slf4j
public class Weather {

  private WeatherType currentWeather;
  private final 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);
  }

  /**
   * 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);
    }
  }
}

执行示例:

java 复制代码
    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

🔍类图


🔍扩展延伸

观察者模式在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部分代码:
java 复制代码
public interface RequestFutureListener<T> {

    void onSuccess(T value);

    void onFailure(RuntimeException e);
}
RequestFuture部分代码:
java 复制代码
public class RequestFuture<T> implements ConsumerNetworkClient.PollCondition {

    private static final Object INCOMPLETE_SENTINEL = new Object();
    private final AtomicReference<Object> result = new AtomicReference<>(INCOMPLETE_SENTINEL);
    private final ConcurrentLinkedQueue<RequestFutureListener<T>> 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<T> listener = listeners.poll();
            if (listener == null)
                break;
            listener.onSuccess(value);
        }
    }
//遍历listener并调用其fail时的方法
    private void fireFailure() {
        RuntimeException exception = exception();
        while (true) {
            RequestFutureListener<T> listener = listeners.poll();
            if (listener == null)
                break;
            listener.onFailure(exception);
        }
    }
    //增加listener
    public void addListener(RequestFutureListener<T> listener) {
        this.listeners.add(listener);
        if (failed())
            fireFailure();
        else if (succeeded())
            fireSuccess();
    }

🔍适用场景


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

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

🔍Ending


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

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

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

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


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

相关推荐
aini_lovee几秒前
MATLAB基于小波技术的图像融合实现
开发语言·人工智能·matlab
堕2745 分钟前
java数据结构当中的《排序》(一 )
java·数据结构·排序算法
R1nG86313 分钟前
多线程安全设计 CANN Runtime关键数据结构的锁优化
开发语言·cann
初次见面我叫泰隆14 分钟前
Qt——5、Qt系统相关
开发语言·qt·客户端开发
亓才孓19 分钟前
[Class的应用]获取类的信息
java·开发语言
开开心心就好27 分钟前
AI人声伴奏分离工具,离线提取伴奏K歌用
java·linux·开发语言·网络·人工智能·电脑·blender
Never_Satisfied30 分钟前
在JavaScript / HTML中,关于querySelectorAll方法
开发语言·javascript·html
80530单词突击赢40 分钟前
JavaWeb进阶:SpringBoot核心与Bean管理
java·spring boot·后端
3GPP仿真实验室1 小时前
【Matlab源码】6G候选波形:OFDM-IM 增强仿真平台 DM、CI
开发语言·matlab·ci/cd
devmoon1 小时前
在 Polkadot 上部署独立区块链Paseo 测试网实战部署指南
开发语言·安全·区块链·polkadot·erc-20·测试网·独立链