I am writing an application that receives different kinds of messages from an external device. The messages are of different types and they are received from the device in the form of a string.

For each message type, there exists a DTO object representing the parsed message, and a parser class which parses the string message into the DTO.

I would like to implement a MessageHandler class which receives messages, parses the messages by using the correct parser, and provides a means for the client to provide handlers for the different kinds of messages.

I have come up with the following design:

internal class MessageHandler
{
    public event EventHandler<MessageTypeAEventArgs>? MessageAReceived;
    public event EventHandler<MessageTypeBEventArgs>? MessageBReceived;

    public void HandleMessage(string message)
    {
        MessageType type = GetMessageType(message);
        switch (type)
        {
            case MessageType.A:
                MessageA messageA = _typeAMessageParser.Parse(message);
                MessageAReceived?.Invoke(this, messageA);
                break;
            case MessageType.B:
                MessageB messageB = _typeBMessageParser.Parse(message);
                MessageBReceived?.Invoke(this, messageB);
                break;
            default:
                break;
        }
    }
}

When a message is received, the client invokes HandleMessage to pass the string message to the MessageHandler. The client can provide handlers by subscribing to the different kinds of events.

I am not convinced that this is a good design. I am looking for suggestions or design patterns which could help me improve it.

4