反对const有一些很好的论据,这里是我的看法:-
就个人而言,我不会将这些“OnXXXUpdated”作为我的经理课程的一部分。我认为这就是为什么在最佳实践方面存在一些混淆。您正在通知相关方某事,并且不知道在通知过程中对象的状态是否会发生变化。它可能会,也可能不会。对我来说显而易见的是,通知相关方的过程应该是一个常量。
所以,为了解决这个困境,这就是我要做的:
从管理器类中删除 OnXXXXUpdated 函数。
编写一个通知管理器,这是一个原型,具有以下假设:
“Args”是一个任意基类,用于在通知发生时传递信息
“Delegate”是某种函数指针(例如 FastDelegate)。
class Args
{
};
class NotificationManager
{
private:
class NotifyEntry
{
private:
std::list<Delegate> m_Delegates;
public:
NotifyEntry(){};
void raise(const Args& _args) const
{
for(std::list<Delegate>::const_iterator cit(m_Delegates.begin());
cit != m_Delegates.end();
++cit)
(*cit)(_args);
};
NotifyEntry& operator += (Delegate _delegate) {m_Delegates.push_back(_delegate); return(*this); };
}; // eo class NotifyEntry
std::map<std::string, NotifyEntry*> m_Entries;
public:
// ctor, dtor, etc....
// methods
void register(const std::string& _name); // register a notification ...
void unRegister(const std::string& _name); // unregister it ...
// Notify interested parties
void notify(const std::string& _name, const Args& _args) const
{
std::map<std::string, NotifyEntry*>::const_iterator cit = m_Entries.find(_name);
if(cit != m_Entries.end())
cit.second->raise(_args);
}; // eo notify
// Tell the manager we're interested in an event
void listenFor(const std::string& _name, Delegate _delegate)
{
std::map<std::string, NotifyEntry*>::const_iterator cit = m_Entries.find(_name);
if(cit != m_Entries.end())
(*cit.second) += _delegate;
}; // eo listenFor
}; // eo class NotifyManager
正如您可能知道的那样,我已经遗漏了一些代码,但您明白了。我想这个通知管理器将是一个单身人士。现在,确保在早期创建通知管理器,其余的管理器只需在构造函数中注册他们的通知,如下所示:
MyManager::MyManager()
{
NotificationMananger.getSingleton().register("OnABCUpdated");
NotificationMananger.getSingleton().register("OnXYZUpdated");
};
AnotherManager::AnotherManager()
{
NotificationManager.getSingleton().register("TheFoxIsInTheHenHouse");
};
现在,当您的经理需要通知相关方时,它只需调用 notify:
MyManager::someFunction()
{
CustomArgs args; // custom arguments derived from Args
NotificationManager::getSingleton().notify("OnABCUpdated", args);
};
其他类可以收听这些东西。
我意识到我刚刚输入了观察者模式,但我的意图是表明问题在于这些东西是如何被提出的,以及它们是否处于 const 状态。通过从管理器类中抽象出通知过程,通知的接收者可以自由地修改该管理器类。只是不是通知管理器。我认为这是公平的。
此外,恕我直言,在一个地方发出通知是一个很好的做法,因为它为您提供了一个可以跟踪通知的地方。