A program receives a list of Messages (base type). Each message in the list has to be processed according to it’s type (descendant type). However, different messages need different inputs in order to be processed correctly.
What is the following technique called? (I haven’t checked this code in a compiler)
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(); }
And this one?
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'); } }
And what is it called if I can inject the ProcessBuilder class into a MessageProcessor (using a property or Setter) and then call Process?
What technique would be the best pattern for solving this problem?
They are both examples of the factory method pattern. The only difference is that the second example has the method in its own static class.
This would be an example of the abstract factory pattern:
Each MessageProcessor gets its own factory class which makes use of polymorphism.
Passing a ProcessBuilder to create the process would be the strategy pattern:
The simplest solution would be to encapsulate a factory method:
If it’s a small known number of types, you can use the series of type checks:
Otherwise use a dictionary: