程序接收消息列表(基本类型).列表中的每条消息都必须根据其类型(后代类型)进行处理.但是,不同的消息需要不同的输入才能正确处理.
下面介绍的技术是什么?(我没有在编译器中检查过这段代码)
abstract class MessageProcessor { public static MessageProcessor GetProcessor(Message message, DataDomain data) { if (message.GetType() == typeof(FooMessage)) { return new FooMessageProcessor(message, data.Name, data.Classification); } else if (message.GetType() == typeof(BarMessage)) { return new BarMessageProcessor(message, data.AccountNo, data.CreditLimit); } else throw new SomeException("Unrecognized type"); } public abstract void Process(); }
还有这个?
static class MessageProcessorFactory { public static MessageProcessor GetProcessor(Message message, DataDomain data) { if (message.GetType() == typeof(FooMessage)) { return new FooMessageProcessor(message, data.Name, data.Classification); } else if (message.GetType() == typeof(BarMessage)) { return new BarMessageProcessor(message, data.AccountNo, data.CreditLimit); } else throw new SomeException("Unrecognized type"); } }
如果我可以将ProcessBuilder类注入MessageProcessor(使用属性或Setter)然后调用Process,它会被调用什么?
什么技术是解决这个问题的最佳模式?
它们都是工厂方法模式的示例.唯一的区别是第二个示例在自己的静态类中有方法.
这将是抽象工厂模式的一个例子:
abstract class MessageProcessorFactory { public abstract MessageProcessor GetProcessor (Message message, DataDomain data); } class FooMessageProcessorFactory : MessageProcessorFactory { public override MessageProcessor GetProcessor (Message message, DataDomain data) { return new FooMessageProcessor(data.Name, data.Classification); } }
每个MessageProcessor都有自己的工厂类,它使用多态.
传递ProcessBuilder来创建流程将是策略模式:
class MessageProcessor { ProcessBuilder builder; public MessageProcessor(ProcessBuilder builder) { this.builder = builder; } public void Process() { builder.BuildMessage(); builder.BuildProcess(); builder.Process(); } } var mp = new MessageProcessor(new FooProcessBuilder());
最简单的解决方案是封装工厂方法:
static void Process(Message msg, DataDomain data) { var p = getProcessor(msg.GetType()); p.Process(msg, data); }
如果它是一个很小的已知类型,您可以使用一系列类型检查:
private static MessageProcessor getProcessor(Type msgType) { return (msgType == typeof(FooMessage)) ? new FooMessageProcessor() : (msgType == typeof(BarMessage)) ? new BarMessageProcessor() : new DefaultMessageProcessor(); }
否则使用字典:
Dictionaryprocessors; private static MessageProcessor getProcessor(Type msgType) { return processors[msgType]; }