观察者模式:
将对象的状态变化,自动通知到所有 动态的 依赖对象。(更常用的是全局事件管理器,或者将依赖对象的管理放到 observer 中实现,如 UE 的 Delegates)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class MainObject { public: void AddNotifyListener(Observer* observer); void RemoveNotifyListener(Observer* observer); void Notify(){ for(auto observer : m_Observers) { observer->OnNotify(); } } private: List<Observer*> m_Observers; };
class Observer { public: virtual void OnNotify() {}; Observer(MainObject* mainObject) : m_MainObject(mainObject) { MainObject->AddNotifyListener(this); } virtual ~Observer(){ MainObject->RemoveNotifyListener(this); MainObject = nullptr; } protected: MainObject* m_MainObject; };
|