Design pattern to avoid downcasting in message passing

前端 未结 3 1477
孤城傲影
孤城傲影 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:40

    You can use a visitor pattern.

    but a visitor should know each of subtypes and define an action for it, so no default action, AFAIK

    class Visitor;
    class BaseMsg {
    //..
    public:
    virtual void acceptVisitor(Visitor * v) = 0;
    };
    
    class Msg1;
    class Msg2;
    class Visitor {     
    // You can put here pure virtuals for sure every visitor will implement them
    public:
    virtual void action (Msg1 * msg) = 0;
    virtual void action (Msg2 * msg) = 0;
    };
    
    class Msg1: public BaseMsg {
    //..
    public:
    void acceptVisitor(Visitor * v){v->action(this);}
    };
    
    class Msg2: public BaseMsg  {
    //..
    public:
    void acceptVisitor(Visitor * v){v->action(this);}
    };
    
    
    
    class Visitor1 : public Visitor {
    // ...
    public:
    void action (Msg1 * msg) {/*...*/ cout << "I like the message!\n";}
    void action (Msg2 * msg) {/*...*/ cout << "I hate the message!\n";}
    // more messages and actions for them
    };
    
    class Visitor2 : public Visitor{
    // ...
    public:
    void action (Msg1 * msg) {/*...*/ cout << "Just fine\n";}
    void action (Msg2 * msg) {/*...*/ cout << "Sorry, I'm busy\n";}
    // more messages and actions for them
    };
    
    int main() {
    
    BaseMsg * a = new Msg1;
    BaseMsg * b = new Msg2;
    
    Visitor * act = new Visitor1;
    Visitor * lazy = new Visitor2;
    // ............
    // somewhere in a deep deep forest of your code
    
    a->acceptVisitor(act);
    b->acceptVisitor(act);
    
    // somewhere else
    
    a->acceptVisitor(lazy);
    b->acceptVisitor(lazy);
    
    delete act;
    delete lazy;
    delete a;
    delete b;
    return 0;
    }  
    

    Output:

    • I like the message!
    • I hate the message!
    • Just fine
    • Sorry, I'm busy

提交回复
热议问题