我正在創建一種機制,通過該機制,接收者可以告訴發件人每個Receiver對某種類型的消息感興趣。與我的樣本實現下面存在一個限制,其中想要接收器接收的某些基本類型僅接收是該類型的顯式和的郵件將不會收到派生類型的消息(見主所有消息()例如)。如何查找對象祖先的類型?
的潛在解決方案將是登記該特定消息時,註冊所有消息的祖先的類型,正確使用這些信息來路由消息。
有沒有什麼其他的解決方案?
注:在現實中,我會保存RTTI所以RTTI查找不會每次都需要。還有其他的東西,我也在這裏掠過/跳過。我要爲簡潔瓦特/這個例子......下面
示例代碼:
class Sender
{
typdef std::vector<Receiver const & > Receivers;
public:
void register(Receiver const & i_recv, typeinfo const & i_type)
{
m_routingMap[i_type].push_back(i_recv);
}
void send(BaseMsg const & i_msg)
{
Receivers receivers = m_routingMap.find(typeid(i_msg));
for (Receivers::iterator receiver = receivers.begin(); receiver != receivers.end(); ++receiver) {
receiver.receive(i_msg);
}
}
private:
std::map<typeinfo const &, Receivers> m_routingMap;
};
class Receiver
{
public:
void receiver(BaseMsg const & i_msg)
{
// React to expected messages here
}
};
class BaseMsg {};
class ChildMsg : public BaseMsg {};
int main()
{
Sender sndr;
Receiver recv1;
sndr.register(recv1, typeid(BaseMsg));
Receiver recv2;
sndr.register(recv2, typeid(ChildMsg));
BaseMsg baseMsg;
sndr.send(baseMsg); // I want only recv1 to receive this message
ChildMsg childMsg;
sndr.send(childMsg); // I want both Receivers to receive this message, but only recv2 will receive it
}
更新:這是我得到了一個解決方案:
// Note: implementation is based in gleaning from
// http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14
class BaseMsg
{
public:
typedef std::vector<TypeInfo const & > Types;
static TypeInfo const * getType()
{
TypeInfo static * ms_type = new TypeInfo(typeid(BaseMsg));
return ms_type;
}
static Types const * getAncestorTypes()
{
// The base class does not have an ancestor
// Static varible, will only be constructed once!
Types * ms_ancestorTypes = new Types();
return ms_ancestorTypes;
}
};
class ChildMsg
{
public:
static TypeInfo const * getType()
{
TypeInfo static * ms_type = new TypeInfo(typeid(ChildMsg));
return ms_type;
}
static Types const * getAncestorTypes()
{
// Add the parent type and all the parent's ancestor's types
Types const * ancestorTypes = BaseMsg::getAncestorTypes();
// Static variable, so it will only be constructed once!
Types * static ms_ancestorTypes = new Types(ancestorTypes->begin(), ancestorTypes->end());
// This push_back() will occur every time, but it's only one operation,
// so hopefully it's not a big deal!
ms_ancestorTypes->push_back(BaseMsg::getType());
return ms_ancestorTypes;
}
};
和發件人:
# Python pseudo code
class Sender:
def send(self, i_msg):
types_to_check_for = [i_msg.getType()].extend(i_msg.getAncestorTypes())
for type_ in types_to_check_for:
for receiver in _routing_list[type_]:
receiver.receive(i_msg)
我的職位是需要的信息識別系統。 – 2012-03-22 20:01:27
請注意:此代碼未編譯,僅作爲示例。 – 2012-03-22 20:34:37
這並沒有解決我試圖解決的特定問題。請參閱我的main()以查看相關問題。 – 2012-03-22 23:27:29