关于观察者模式中单个观察者需监听多个被观察者的实现疑问
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

