Suppose I have a baseclass called IMessage, and lots of derived message classes.
In my program I have one method that receives all messages :
void ReceiveMessage(IMessage message)
{
}
and I’d like to call a specific method for each type of message.
It would be great if I could do :
void ReceiveMessage(IMessage message)
{
HandleMessage(message);
}
void HandleMessage(DummyMessage message)
{
Blah;
}
void HandleMessage(SillyMessage message)
{
Yuk;
}
..but apparently “we ain’t going out like that“.
So how would I go about implementing specific handlers for specific messages, being called from a single messagehandler ?
The classic way to handle this type of situation is via the Visitor pattern.
That being said, you can actually handle this a bit easier in C# via
dynamic, like so:The dynamic binding engine will find, at runtime, the “best” match for your specific message type, and route the call to the appropriate method.