Design pattern for loading multiple message types

Posted by lukem00 on Stack Overflow See other posts from Stack Overflow or by lukem00
Published on 2010-06-16T19:17:43Z Indexed on 2010/06/16 19:22 UTC
Read the original article Hit count: 178

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET