You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于观察者模式中单个观察者需监听多个被观察者的实现疑问

关于观察者模式中单个观察者需监听多个被观察者的实现疑问

Hey folks! I’ve been really digging into the observer pattern lately, and I wrote a little C++ demo snippet to help me understand it better. But right after wrapping up the demo, a question popped into my head— the standard observer pattern is set up for one observable object with multiple observers, right? So what do I do when an observer needs to receive updates from two or more different observables?

Here’s the demo code I put together (pay attention to the core structure, even though some parts are truncated):

#include<list>
#include<algorithm>
#include<iostream>
#include<string>

class IObserver;

class IObservable
{
public:
    virtual void add(IObserver*) = 0;
    virtual void remove(IObserver*) = 0;
    virtual void trigger() = 0;
    virtual double get_temperature() = 0;
    virtual ~IObservable() = default;
};

class IObserver
{
public:
    IObserver(IObservable& observable):m_observable(observable){}
    virtual void update() = 0;
    virtual ~IObserver() = default;
protected:
    IObservable& m_observable;
};

I’m stuck on figuring out how to adapt this pattern to let an observer listen to multiple sources. Any thoughts or solutions would be really appreciated!

备注:内容来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 10:14:38