Design pattern for handling multiple message types

前端 未结 10 1068
甜味超标
甜味超标 2020-11-28 03:13

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.

F

10条回答
  •  野性不改
    2020-11-28 03:51

    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;
            ...
        }
    }
    

提交回复
热议问题