有針對常量一些很好的理由,這裏所以這裏是我的看法: -
個人而言,我不會有這些「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