我想实现一个不改变模型的模型类的观察者。因此,它应该能够使用 const-Reference 来访问模型。但观察员登记禁止这样做。
以下是我的项目中如何实现观察者模式:
//Attributes of type Observable are used by classes that want to notify others
//of state changes. Observing Objects register themselves with AddObserver.
//The Observable Object calls NotifyObservers when necessary.
class Notifier
{
public:
AddObserver(Observer*);
RemoveObserver(Observer*);
NotifyObservers();
};
class Model
{
public:
Notifier& GetNotifier() //Is non const because it needs to return a non-const
{ //reference to allow Observers to register themselves.
return m_Notifier;
}
int QueryState() const;
void ChangeModel(int newState)
{
m_Notifier.NotifyObservers();
}
private:
Notifier m_Notifier;
};
//This View does not Modify the Model.
class MyNonModifingView : public Observer
{
public:
SetModel(Model* aModel) //should be const Model* aModel...
{
m_Model = aModel;
m_Model->GetNotifier().AddObserver(this); //...but can't because
//SetModel needs to call GetNotifier and add itself, which requires
//non-const AddObserver and GetNotifier methods.
}
void Update() //Part of Observer-Interface, called by Notifiers
{
m_Model->QueryState();
}
};
非修改观察者需要“更改”模型的唯一地方是它想要注册它的时候。我觉得我无法避免 const_cast 这里,但我想知道是否有更好的解决方案。
旁注:换句话说,我不认为模型对象管理的“观察者列表”是模型状态的一部分。C++ 无法区分并将状态和观察者混为一谈,迫使两者都是 const 或 non-const。
干杯,菲利克斯