How do I call different methods for different types of classes in a common message sink?
Suppose I have a base class named IMessage and many derived message classes.
In my program, I have one method that receives all messages:
void ReceiveMessage(IMessage message)
{
}
and I would like to call a specific method for each post type. It would be great if I could:
void ReceiveMessage(IMessage message)
{
HandleMessage(message);
}
void HandleMessage(DummyMessage message)
{
Blah;
}
void HandleMessage(SillyMessage message)
{
Yuk;
}
.. but apparently "we're not going like that."
So how can I implement specific handlers for specific messages called from a single message handler?
source to share
The classic way to deal with this type of situation is with the visitor pattern .
That being said, you can handle it a little easier in C # via dynamic
, for example:
void ReceiveMessage(IMessage message)
{
dynamic specificMessage = message;
this.HandleMessage(specificMessage):
}
The dynamic binding engine will find the "best" match for your particular message type at run time and route the call to the appropriate method.
source to share
Your IMessage interface must define a HandleMessage () function that each type implements:
public interface IMessage
{
void HandleMessage();
}
public class DummyMessage : IMessage
{
public void HandleMessage()
{
Blah;
}
}
public class SillyMessage : IMessage
{
public void HandleMessage()
{
Yak;
}
}
Then you would call it like this:
void ReceiveMessage(IMessage message)
{
message.HandleMessage();
}
source to share
It is possible to do what you suggest, although this is not very DRY and I think the other suggestions are more appropriate here. That said, in the interest of completeness, here's an approach that's close to what you were originally looking for:
void ReceiveMessage( IMessage message ) {
if( message as DummyMessage != null ) HandleMessage( message as DummyMessage );
else if( message as SillyMessage != null ) HandleMessage( message as SillyMessage );
// etc
}
source to share