我正在使用外部库,需要创建一个观察者模式,其中观察者来自属于该库的对象.我不想从库中更改基类,同时我必须使用这个不可更改的基类的引用/指针列表.除此之外,库构造了对象列表,我需要从中筛选出适合观察者的对象.
我写的代码大致相当于:
#include <iostream>
#include <vector>
#include <memory>
// This class is from an external library which I don't want to chagne
class BaseFromLibrary {
public:
virtual ~BaseFromLibrary() {}
};
class BaseOfObserver {
public:
void notify() { std::cout << "What-ho!\n"; };
};
class Observer : public BaseFromLibrary, public BaseOfObserver {};
class Subject {
public:
std::vector<std::shared_ptr<Observer>> observers;
void notifyObervers() {
for (auto &o : observers)
(*o).notify();
}
};
int main() {
// This list is constructed by the library and I …Run Code Online (Sandbox Code Playgroud)