Design pattern to avoid downcasting in message passing

前端 未结 3 1474
孤城傲影
孤城傲影 2021-02-06 18:39

Base class MessageHandler has derived classes. They would like to pass messages to each other. Messages could be of different classes, but can be made to share a ba

3条回答
  •  醉话见心
    2021-02-06 19:32

    If I'm understanding your question correctly, you just need straight inheritance with a virtual function. Something like:

    class BaseMessage 
    {
        public:
        virtual ~BaseMessage() {}
    
        virtual void processMsg() = 0;
    };
    
    class MessageA : public BaseMessage
    {
        public:
        MessageA() {}
        virtual ~MessageA() {}    
        virtual void processMsg()
        {
            // ... do something for MessageA ...
        }
    };
    
    class MessageB : public BaseMessage
    {
        public:
        MessageB() {}
        virtual ~MessageB() {}    
        virtual void processMsg()
        {
            // ... do something for MessageB ...
        }
    };
    

    Where you handle the message, simply call the processMsg() function on the message you receive to process each message as specified in each class.

    std::auto_ptr m(mailbox.getMessage()); // Returns whatever msg is sent to your handler
    m->processMsg();
    

提交回复
热议问题