考虑到您的问题,我将执行以下操作:
- 对每条消息使用对象表示
- 使用诸如责任链之类的模式来根据消息的类型来处理消息。
这种架构的优点是您可以分离每种消息类型的处理逻辑。这允许您快速扩展它(添加新的消息处理程序或新的消息类型),而不会影响系统的其余部分。此外,您可以使用多态性来允许单个处理程序处理多种消息类型(在您的情况下为 ForwardHandler)。
这是一个简单的实现示例。
首先,消息类型:
public abstract class BaseMessage { ... } // base class inherited by every message
public abstract class ForwardableMessage : BaseMessage { ... } // base class for message that should only be forwarded
public class MessageOfTypeA : BaseMessage { ... } // a message of type A (which is not forwardable)
public class MessageOfTypeB : ForwardableMessage { ... } // a message of type B (which is forwardable)
public class MessageOfTypeC : ForwardableMessage { ... } // a message of type C (which is forwardable)
(请注意,在这种情况下,使用可转发消息的接口可能会更灵活,我会对人们对此事的看法感兴趣)。
其次,定义您的处理程序:
public abstract class BaseMessageHandler {
public abstract bool CanHandle(BaseMessage msgToHandle)
public abstract void Handle(BaseMessage msgToHandle);
}
public class MessageForwarderHandler : BaseMessageHandler {
public bool CanHandle(BaseMessage msgToHandle)
{
return msgToHandle is ForwardableMessage;
}
public void Handle(BaseMessage msgToHandle)
{
// do the forwarding logic here
}
}
public class MessageOfTypeAHandler : BaseMessageHandler {
public bool CanHandle(BaseMessage msgToHandle)
{
return msgToHandle is MessageOfTypeA;
}
public void Handle(BaseMessage msgToHandle)
{
// do the logic specific to messages of type A
}
}
最后,您必须实现一个维护不同处理程序列表的对象。
public static class MessageHandlersProvider
{
IEnumerable<MessageHandler> handlers = new List<MessageHandler>()
{
new MessageOfTypeAHandler(),
new MessageForwarderHandler()
}
public static void HandleMessage(BaseMessage msg)
{
foreach (MessageHandler handler in handlers)
{
if (handler.CanHandle(msg))
{
handler.Handle(msg);
// you may stop once you have found a handler that can handle or you might consider that multiple handlers can be applied to the same message
}
}
}
}
这个解决方案确实需要为每条消息创建一个对象实例,但在我看来,它要优雅得多。