Model を変更しない Model クラスの Observer を実装したいと考えています。したがって、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 または非 const に強制します。
乾杯、フェリックス