Design pattern for loading multiple message types
- by lukem00
As I was looking through SO I came across a question about handling multiple message types. My concern is - how do I load such a message in a neat way? I decided to have a separate class with a method which loads one message each time it's invoked. This method should create a new instance of a concrete message type (say AlphaMessage, BetaMessage, GammaMessage, etc.) and return it as a Message.
class MessageLoader
{
public Message Load()
{
// ...
}
}
The code inside the method is something which looks really awful to me and I would very much like to refactor it/get rid of it:
Message msg = Message.Load(...); // load yourself from whatever source
if (msg.Type == MessageType.Alpha) return new AlphaMessage(msg);
if (msg.Type == MessageType.Beta) return new BetaMessage(msg);
// ...
In fact, if the whole design looks just too messy and you guys have a better solution, I'm ready to restructure the whole thing.
If my description is too chaotic, please let me know what it's missing and I shall edit the question. Thank you all.