有针对常量一些很好的理由,这里所以这里是我的看法: -
个人而言,我不会有这些“OnXXXUpdated”作为我的经理类的一部分。我认为这就是为什么最佳实践存在一些困惑。您正在通知感兴趣的各方有关某事的信息,并且不知道在通知过程中对象的状态是否会发生变化。它可能,也可能不会。什么是对我来说很明显,是通知感兴趣方应该是一个常量的过程。
因此,要解决这一难题,这是我会做什么:
从你的管理类摆脱OnXXXXUpdated功能。
写通知管理器,这里有一个原型,具有以下假设:
“参数数量”是任意基类出于传递信息通知时发生
“委派”是某种一个函数指针(例如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");
};
,当你的经理需要通知有关方面,它只是电话通知:
MyManager::someFunction()
{
CustomArgs args; // custom arguments derived from Args
NotificationManager::getSingleton().notify("OnABCUpdated", args);
};
其他类可以听这个东西。
我意识到我刚刚输入了Observer模式,但我的目的是要表明问题在于如何提出这些事情,以及它们是否处于常量状态。通过从Mananager类中抽象出通知的过程,通知的接收者可以自由修改该经理类。只是不是通知管理员。我认为这很公平。
此外,有一个单一的地方来提高通知是好的实践,因为它给你一个地方,你可以跟踪你的通知。
我想你是赞成声明方法const? – starblue 2010-10-27 19:33:53
如果这是代码审查,我可能不会反对任何方式,除非有其他因素在起作用。如果每个人都访问全局,并且没有传递const引用,那真的没关系。我坚决不同意静态分析可以告诉你这个方法应该是const的前提:静态分析告诉你它*可以*是const *被实现的*,但它不知道你是否打算稍后增强函数(例如与统计,或消息排队或重复删除或你有什么)。 – 2010-10-27 21:02:06