46

I've got the GOF sitting on my desk here and I know there must be some kind of design pattern that solves the problem I'm having, but man I can't figure it out.

For simplicities sake, I've changed the name of some of the interfaces that I'm using.

So here's the problem, on one side of the wire, I've got multiple servers that send out different types of messages. On the other side of the wire I have a client that needs to be able to handle all the different types of messages.

All messages implement the same common interface IMessage. My problem is, when the client gets a new IMessage, how does it know what type of IMessage its received?

I supposed I could do something like the following, but this just FEELS awful.

TradeMessage tMessage = newMessage as TradeMessage;
if (tMessage != null)
{
    ProcessTradeMessage(tMessage);
}

OrderMessage oMessage = newMessage as OrderMessage;
if (oMessage != null)
{
    ProcessOrderMessage(oMessage);
}

The second thought, is to add a property to IMessage called MessageTypeID, but that would require me to write something like the following, which also FEELS awful.

TradeMessage tMessage = new TradeMessage();
if (newMessage.MessageTypeID == tMessage.MessageTypeID)
{
    tMessage = newMessage as TradeMessage;
    ProcessTradeMessage(tMessage); 
}

OrderMessage oMessage = new OrderMessage();
if (newMessage.MessageTypeID == oMessage.MessageTypeID)
{
    oMessage = newMessage as OrderMessage;
    ProcessOrderMessage(oMessage);
}

I know this general problem has been tackled a million times, so there has to be a nicer way of solving the problem of having a method that takes an interface as a parameter, but needs different flow control based on what class has implemented that interface.

1
  • I added an answer similar to the one you accepted that works off of @Brian Gideon's suggestion which I think you will find works well using Double Dispatching.
    – SwDevMan81
    May 7, 2013 at 12:34

11 Answers 11

28

You could create separate message handlers for each message type, and naively pass the message to each available handler until you find one that can handle it. Similar to the chain of responsibility pattern:

public interface IMessageHandler {
    bool HandleMessage( IMessage msg );
}

public class OrderMessageHandler : IMessageHandler {
    bool HandleMessage( IMessage msg ) {
       if ( !(msg is OrderMessage)) return false;

       // Handle the message and return true to indicate it was handled
       return true; 
    }
}

public class SomeOtherMessageHandler : IMessageHandler {
    bool HandleMessage( IMessage msg ) {
       if ( !(msg is SomeOtherMessage) ) return false;

       // Handle the message and return true to indicate it was handled
       return true;
    }
}

... etc ...

public class MessageProcessor {
    private List<IMessageHandler> handlers;

    public MessageProcessor() {
       handlers = new List<IMessageHandler>();
       handlers.add(new SomeOtherMessageHandler());
       handlers.add(new OrderMessageHandler());
    }

    public void ProcessMessage( IMessage msg ) {
       bool messageWasHandled
       foreach( IMessageHandler handler in handlers ) {
           if ( handler.HandleMessage(msg) ) {
               messageWasHandled = true;
               break;
           }
       }

       if ( !messageWasHandled ) {
          // Do some default processing, throw error, whatever.
       }
    }
}

You could also implement this as a map, with the message class name or message type id as a key and the appropriate handler instance as the value.

Others have suggested having the message object "handle" itself, but that just doesn't feel right to me. Seems like it would be best to separate the handling of the message from the message itself.

Some other things I like about it:

  1. You can inject the message handlers via spring or what-have-you rather than creating them in the constructor, making this very testable.

  2. You can introduce topic-like behavior where you have multiple handlers for a single message by simply removing the "break" from the ProcessMessage loop.

  3. By separating the message from the handler, you can have different handlers for the same message at different destinations (e.g. multiple MessageProcessor classes that handle the same messages differently)

5
  • 1
    All the solutions were great, but this one fit the needs of this application best. a TradeMessage would not be processed the same by all applications, so it didn't make sense to put the processing logic into the TradeMessage object. Sep 25, 2009 at 16:29
  • 2
    if (!msg is SomeOtherMessage) should be if (!(msg is SomeOtherMessage)). OrderMessageHandler and SomeOtherMessageHandler should implement IMessageHandler to be able to add them to the List<IMessageHandler> handlers. Also bool messageWasHandled misses a ;. (Did you actually test this?)
    – Kapé
    Apr 7, 2015 at 14:59
  • Hi, Is serializate/deserialize part of the problem/solution too ?
    – ransh
    Apr 26, 2015 at 5:31
  • This feels like the Chain of Responsibility pattern to me, do we agree?
    – FoxDeploy
    Jan 16, 2022 at 3:41
  • Hello, I would like to ask: if each of my handlers were to return a different object ie TradeDataDecoder, AskDecoder, BidDecoder etc. for at least 15 separate objects, and each object does not implement or extend anything. How should I write the ProcessMessage method so that I can return that object and be able to access the decoded data within? I m supposed to process the data from a byte[] so I cant tell which object the data should be, but if i upcast and return an object I dont know which of the 15 objects to cast the returned value to Jan 30 at 7:41
16

A couple of solutions are applicable for this, first is best solution, last is least best. All examples are pseudocode:

1st, and best solution

Vincent Ramdhanie introduced the actual correct pattern to solve this problem, which is called the strategy pattern.

This pattern creates a separate 'processor', in this case to process the messages accordingly.

But I'm pretty sure a good explanation is given in your book by the GOF :)

2nd

As commented, the message may not be able to process itself, it is still usefull to create an interface for the message, or a base class, so you can make a general processing function for a message, and overload it for more specific ones.

overloading is in any case better then creating a different method for every type of message...

public class Message {}
public class TradeMessage extends Message {}

public class MessageProcessor {
    public function process(Message msg) {
        //logic
    }

    public function process(TradeMessage msg) {
        //logic
    }
}

3rd

If your message could process itself you could write an interface, since your process method depends on what message you got, it seems easier to put it inside the message class...

public interface IMessage
{
    public function process(){}
}

you then implement this in all your message classes and proccess them:

list = List<IMessage>();
foreach (IMessage message in list) {
    message.process();
}

in your list you can store any class that implements that interface...

6
  • 1
    I kind of assumed that his ProcessXMessage() function hinged on code outside of his object, so his object could not internally process itself.
    – JustLoren
    Sep 25, 2009 at 14:14
  • As I understand the problem, the message might not have any behavior associated with it. So I think a separate message processor with that behavior overloaded would be the best solution. Sep 25, 2009 at 14:15
  • @bruno conde: Much like Vincent Ramdhanie's post - I agree, this is probably the best overall implementation.
    – JustLoren
    Sep 25, 2009 at 14:19
  • If overloading isn't working for you, you can always pass the Processor into the IMessage.process() method and then have it do an explicit callback to the appropriate method on the Processor using a double-dispatch technique. Sep 25, 2009 at 14:38
  • 1
    You're correct JustLoren, the messages can not process themselves. The processing of the message depends on the client that receives them. The message might be written to a database, displayed on the screen, or simply stored in a local cache. Sep 25, 2009 at 15:03
9

From my experience with message handling, its usually the case that different consumers of messages require handling a variety of message types. I found the Double Dispatch pattern to handle this nicely. The basic idea is to register a set of handlers that dispatch the received messages to the handler for processing based on the specific type (using function overloading). The consumers only register for the specific types they wish to receive. Below is a class diagram.

Double Dispatch UML Class Diagram

The code looks like this:

IHandler

public interface IHandler
{
}

IMessageHandler

public interface IMessageHandler<MessageType> : IHandler
{
   void ProcessMessage(MessageType message);
}

IMessage

public interface IMessage
{
   void Dispatch(IHandler handler);
}

MessageBase

public class MessageBase<MessageType> : IMessage
   where MessageType : class, IMessage
{
   public void Dispatch(IHandler handler)
   {
      MessageType msg_as_msg_type = this as MessageType;
      if (msg_as_msg_type != null)
      {
         DynamicDispatch(handler, msg_as_msg_type);
      }
   }

   protected void DynamicDispatch(IHandler handler, MessageType self)
   {
      IMessageHandler<MessageType> handlerTarget = 
         handler as IMessageHandler<MessageType>;
      if (handlerTarget != null)
      {
         handlerTarget.ProcessMessage(self);
      }
   }
}

DerivedMessageHandlerOne

// Consumer of DerivedMessageOne and DerivedMessageTwo 
// (some task or process that wants to receive messages)
public class DerivedMessageHandlerOne : 
   IMessageHandler<DerivedMessageOne>, 
   IMessageHandler<DerivedMessageTwo>
   // Just add handlers here to process incoming messages
{     
   public DerivedMessageHandlerOne() { }

   #region IMessageHandler<MessaegType> Members

   // ************ handle both messages *************** //
   public void ProcessMessage(DerivedMessageOne message)
   {
     // Received Message one, do something with it
   }

   public void ProcessMessage(DerivedMessageTwo message)
   {
      // Received Message two, do something with it   
   }

   #endregion
}

DerivedMessageOne

public class DerivedMessageOne : MessageBase<DerivedMessageOne>
{
   public int MessageOneField;

   public DerivedMessageOne() { }
}

Then you just have a container that manages the Handlers and you are all set. A simple for loop through the list of Handlers when a message received, and the Handlers receive the messages where they want them

// Receive some message and dispatch it to listeners
IMessage message_received = ...
foreach(IHandler handler in mListOfRegisteredHandlers)
{
   message_received.Dispatch(handler);
}

This design came out of a question I asked awhile back about Polymorphic Event Handling

4
  • What do you mean by container exactly? Oct 20, 2013 at 15:39
  • @ByteBlast - By container I just mean a class that mananges the collection of mListOfRegisteredHandlers. So basically a class that has add/remove handler functions and would maybe have a helper function called DispatchMessage(IMessage msg) that would loop through the list of mListOfRegisteredHandlers and call msg.Dispatch(handler) (the last code snippet in my answer).
    – SwDevMan81
    Oct 21, 2013 at 12:31
  • What would you call this container type? Out of interest - thanks. Oct 21, 2013 at 12:32
  • You could change the declaration to abstract class MessageBase<T> where T : MessageBase<T> in which case, you could immediately cast the message as (T)this. After all you would declare your messages like A : MessageBase<A> anyway. You could also merge the Dispatch(IHandler) and DynamicDispatch(IHandler, T) methods which would become simpler with the previous modification. Unless I overlooked something somewhere.
    – Adam L. S.
    May 25, 2018 at 21:24
4

One option is to have the messages come with their own handlers. That is, create an Interface called IMessageProcessor that specifies a method processMessage(IMessage). Next define concrete class that implements IMessageProcessor for each type of message.

Each IMessage class will then define its own Processor.

When you receieve a message object you will do something like this:

message.processor.processMessage();
3

A dispatching pattern might work well.

public static class MessageDispatcher
{
  private static readonly IMessageHandler s_DefaultHandler =
      new DefaultMessageHandler();
  private static readonly Dictionary<Type, IMessageHandler> s_Handlers =
      new Dictionary<Type, IMessageHandler>();

  static MessageDispatcher()
  {
    // Register a bunch of handlers.
    s_Handlers.Add(typeof(OrderMessage), new OrderMessageHandler());
    s_Handlers.Add(typeof(TradeMessage), new TradeMessageHandler());
  }

  public void Dispatch(IMessage msg)
  {
    Type key = msg.GetType();
    if (s_Handlers.ContainsKey(key))
    {
      // We found a specific handler! :)
      s_Handlers[key].Process(msg);
    }
    else
    {
      // We will have to resort to the default handler. :(
      s_DefaultHandler.Process(msg);
    }
  }
}

public interface IMessageHandler
{
  void Process(IMessage msg);
}

public class OrderMessageHandler : IMessageHandler
{
}

public class TradeMessageHandler : IMessageHandler
{
}

There are all kinds of variations to this theme. They will all have a dispatcher object that contains many different handlers. You should consider a default handler in case the dispatcher cannot find a specific handler. There is a lot of freedom in how you choose to dispatch the messages to the appropriate handlers. I just happen to dispatch based on type, but you could make it arbitrarily more complex. Maybe the dispatcher could examine the contents of the message to discover the best handler. Maybe the message carries with it a key that identifies a preferred handler. I don't know. There are a lot of possibilities here.

3
  • I like this idea. But there are for 2 things I don't love about the implementation: First, if a handler is registered for type A using ContainsKey(Type) will fail for objects of any class derived from A. Second, a Dictionary only allows one handler per type of message.
    – NVRAM
    Sep 25, 2009 at 15:34
  • @NVRAM - I think you can get around the first point by adding the derived types with the same handler. Obviously not ideal, but a work around. The second point is valid.
    – SwDevMan81
    Jun 25, 2013 at 12:09
  • 2
    +1 here: I thought about this option also, but you did already. I would use the Dictionary.TryGetValue() instead of Contains() + Dictionary[KEY] because that will result in two lookups.. This is the same method like my TCP packet handling. Jul 16, 2015 at 14:31
3

For my little messaging framework inside Silverlight app i'm using Mediator pattern. It's some kind of messaging bus/broker, to which objects are subscribing for specific type or types of message. Then this Mediator object (broker/bus) is deciding who will receive what kind of messages.
Someting like:

SubscribeFor<ChatMessage>().If(x=>x.SomeProp==true).Deliver(MyMethod);

Sample methods that are called:

void MyMethod(ChatMessage msg) , or
void MyMethod(BaseBessage msg)

or publishing (broadcasting) of messages:

Publish(new ChatMessage());

BaseMessage is abstract class, which all my messages inherits, and have just reference to sender and some unique Guid.

I took starting point for building my messaging framework from MVVM Light Toolkit, you can take a look at theirs source code, it's not complicated!

If you whish, I can put c# code for this somewhere?

1
2

Add a ProcessMessage() method to the iMessage interface and let the concrete message polymorphically decide the right way to process themselves.

Your code then becomes

newMessage.ProcessMessage();

Here is a good article on using polymorphism instead of conditionals.

0
2

You might want to take a look through Enterprise Integration Patterns by Gregor Hohpe and Bobby Woolf. It has a good catalog of patterns for message processing.

1

In a similar scenario I have a server which receives lots of different messages from multiple clients.

All messages are sent serialized and start with an identifier of message type. I then have a switch statement looking at the identifier. The messages are then deserialized (to very differing objects) and processed as appropriate.

A similar thing could be done by passing objects which implement an interface which includes a way of indicating message type.

public void ProcessMessage(IMessage msg)
{
    switch(msg.GetMsgType())  // GetMsgType() is defined in IMessage
    {
        case MessageTypes.Order:
            ProcessOrder(msg as OrderMessage);  // Or some other processing of order message
            break;
        case MessageTypes.Trade:
            ProcessTrade(msg as TradeMessage); //  Or some other processing of trade message
        break;
        ...
    }
}
2
  • 2
    I've replace usage of this with a dictionary of commands which implement a common interface and are indexed by type. Much less code. Fight large switch statments with this command pattern
    – Matt Lacey
    Nov 12, 2010 at 10:10
  • I'm currently using a switch statement (similar to your example) and would greatly appreciate some more direction and/or pseudo code on this "command pattern"! Thanks! Jan 16, 2020 at 18:34
1

I know this is an older thread, with several very good answers over the years.

However, in 2018, I'd use a package such as Jimmy Bogard's MediatR (https://github.com/jbogard/MediatR).

It provides decoupling of message sending and processing with patterns such as request/response, Command/Query, One-way, Pub/Sub, async, polymorphic dispatching, etc.

0

I know it's super old, but I had to implement something similar today and I just wanted to mention some little useful sidenotes to the accepted answer,

first, to reduce code duplications (is X, is Y) in the concrete Handle implementation, I would recommend making an abstract handler class, so this:

public class OrderMessageHandler : IMessageHandler {
    bool HandleMessage( IMessage msg ) {
       if ( !(msg is OrderMessage)) return false;

       // Handle the message and return true to indicate it was handled
       return true; 
    }
}
public class SomeOtherMessageHandler : IMessageHandler {
    bool HandleMessage( IMessage msg ) {
       if ( !(msg is SomeOtherMessage) ) return false;

       // Handle the message and return true to indicate it was handled
       return true;
    }
}

becomes:

public abstract class MessageHandler<T> : IMessageHandler where T : IMessage
{
    bool HandleMessage(IMessage msg)
    {
        if (!(msg is T concreteMsg)) return false;
        Handle(concreteMsg);
        return true;
    }
    protected abstract void Handle(T msg);
}
public class OrderMessageHandler : MessageHandler<OrderMessage>
{
    protected override void Handle(OrderMessage msg)
    {
        // do something with the concrete OrderMessage type
    }
}
public class SomeOtherMessageHandler : MessageHandler<SomeOtherMessage>
{
    protected override void Handle(SomeOtherMessage msg)
    {
        // do something with the concrete SomeOtherMessage type
    }
}

and yea I would consider using Dictionary<Type, IMessageHandler> instead of foreach and forcing to return bool from handling to decide if it was handled , so my final answer would be:

*(ConcreteType is not a must, it's there to help you to add the handler without specifying the type)

public interface IMessageHandler
{
    Type ConcreteType { get; }
    void HandleMessage(IMessage msg);
}

public abstract class MessageHandlerBase<TConcreteMessage> : IMessageHandler where TConcreteMessage : IMessage
{
    public Type ConcreteType => typeof(TConcreteMessage);
    public void HandleMessage(IMessage msg)
    {
        if (msg is not TConcreteMessage concreteMsg) return;
        Handle(concreteMsg);
    }
    protected abstract void Handle(TConcreteMessage msg);
}

public class OrderMessageHandler : MessageHandlerBase<OrderMessage>
{
    protected override void Handle(OrderMessage msg)
    {
        // do something with the concrete OrderMessage type
    }
}

public class SomeOtherMessageHandler : MessageHandlerBase<SomeOtherMessage>
{
    protected override void Handle(SomeOtherMessage msg)
    {
        // do something with the concrete SomeOtherMessage type
    }
}

public class MessageProcessor
{
    private readonly Dictionary<Type, IMessageHandler> _handlers = new();

    public MessageProcessor()
    {
    }
    public void AddHandler(IMessageHandler handler)
    {
        var concreteMessageType = handler.ConcreteType;
        if (_handlers.ContainsKey(concreteMessageType))
        {
            throw new Exception($"handler for type {concreteMessageType} already exists.");
            //if you want to support multiple handlers for same type it can be solved with dictionary of List<T>
        }
        _handlers[concreteMessageType] = handler;
    }

    public void ProcessMessage(IMessage msg)
    {
        if (_handlers.TryGetValue(msg.GetType(), out var handler))
        {
            handler.HandleMessage(msg);
        }
        else
        {
            // Do some default processing, throw error, whatever.
        }
    }
}

public class OrderMessage : IMessage
{
    public Guid Guid { get; set; }
    public int Number { get; set; }
}

public class SomeOtherMessage : IMessage
{
    public Guid Guid { get; set; }
    public string Text { get; set; }
}

Hope it can help someone in the future :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.