小工具知识网

当前位置: 首页 > 行业知识 > 【设计模式】JAVA Design Patterns——Observer(观察者模式)

行业知识

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

2026-12-04 08:55:34 来源:互联网转载

目的


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

解释


真实世界例子

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

通俗描述

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

维基百科

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

编程示例

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

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

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

@Slf4jpublic 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

类图


扩展延伸 

观察者模式在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):实现了观察者接口的具体对象,负责接收主题对象的通知,并根据通知更新自身状态。

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


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

上一篇:如何关闭优酷会员自动续费?轻松解决教程!

下一篇:Countup.js使用方法详解