Design pattern for loading multiple message types

后端 未结 4 1492
攒了一身酷
攒了一身酷 2021-01-06 10:29

As I was looking through SO I came across a question about handling multiple message types. My concern is - how do I load such a message in a neat way? I decided to have a s

4条回答
  •  天涯浪人
    2021-01-06 10:49

    What you have looks fine. It's unambiguous. If your AlphaMessage and BetaMessage objects are children of Message then instead of creating a new object, just return the object casted.

    if (msg.Type == MessageType.Alpha) return msg as AlphaMessage;
    else if (msg.Type == MessageType.Beta) return msg as BetaMessage;
    

    Consumer code will have to handle the case where the cast fails (as returns null).

提交回复
热议问题