class ObserverBase {
public:
ObserverBase() {}
virtual ~ObserverBase() {}
virtual void Update() {}
};
class ObserverFirstChild : public ObserverBase {
void Update() override {
std::cout << "first child receive notify" << std::endl;
}
};
class ObserverSecondChild : public ObserverBase {
void Update() override {
std::cout << "second child receive notify" << std::endl;
}
};
#include <list>
class NotifyBase {
public:
void Add(ObserverBase* ob) { observers.emplace_back(ob); };
void Remove(ObserverBase* ob) { observers.remove(ob); }
void Notify() {
for (auto observer : observers) {
observer->Update();
}
}
private:
std::list<ObserverBase*> observers;
};
int main() {
ObserverBase* base1 = new ObserverFirstChild();
ObserverBase* base2 = new ObserverSecondChild();
NotifyBase notify;
notify.Add(base2);
notify.Add(base1);
notify.Notify();
notify.Remove(base1);
notify.Notify();
delete base2;
delete base1;
return 0;
}
观察者模式简述
最新推荐文章于 2024-11-13 19:36:04 发布