モデルを変更しないModelクラスのObserverを実装したいと思います。したがって、モデルにアクセスするためにconst-Referenceを使用できるはずです。しかし、オブザーバーの登録はこれを禁止します。ここでObserverパターンのConst-Not Notifier
はオブザーバーパターンは私のプロジェクトで実装されている方法です。
//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の両方を強制します。
は乾杯、フェリックス
私は変更可能で行った。私は以前はさまざまな理由でNotificationMediatorを注入することを検討していましたが、これは今のところ大きな混乱の原因となります。 – TheFogger