代码之家  ›  专栏  ›  技术社区  ›  Vijay Angelo

有没有更好的方法来设计这个消息传递代码?

c++
  •  0
  • Vijay Angelo  · 技术社区  · 15 年前

    A类使用以下两个函数来构建和发送消息1&2.

    builder::prepareAndDeliverMsg1(msg1_arg1,msg1_arg2)
    {
    }
    
    builder::prepareAndDeliverMsg2(msg2_arg1,msg2_arg2)
    {
    }
    

    现在,引入了一个新的B类,它将在两个阶段中完成a所做的工作

    第1阶段->准备 阶段2->传送

    我正在考虑扩展builder类,如下所示:

    ///----
    
    builder::prepareMsg1(msg1_arg1,msg1_arg2)
    {
    }
    
    builder::prepareMsg2(msg2_arg1,msg2_arg2)
    {
    }
    
    builder::deliverMsg1(msg1_arg1)
    {
        This function, inserts re-calculated msg1_arg1 into the prepared message in stage1
    }
    
    builder::deliverMsg2(msg2_arg1)
    {
       This function, inserts re-calculated msg2_arg1 into the prepared message in stage1
    }
    
    // These two functions are still retained for the usage of class A
    builder::prepareAndDeliverMsg1(msg1_arg1,msg1_arg2)
    {
    }
    
    builder::prepareAndDeliverMsg2(msg2_arg1,msg2_arg2)
    {
    }
    
    //---
    

    我想知道,是否有更好的设计方法?

    4 回复  |  直到 15 年前
        1
  •  3
  •   sharptooth    15 年前

    也许对于每条消息,创建自己的类并从基本消息类继承?

    class TBaseMsg
    {
    public:
       virtual void prepare() = 0;
       virtual void deliver() = 0;
    }
    
        2
  •  2
  •   Mykola Golubyev    15 年前

    你可以看看装饰设计模式。

    http://en.wikipedia.org/wiki/Decorator_pattern

        3
  •  1
  •   MiniQuark    15 年前

    我觉得你的解决方案不错。

        4
  •  1
  •   Patrick    15 年前

    class base {
        virtual bool prepareMsg1() = 0;
        virtual bool prepareMsg2() = 0;
        virtual bool deliverMsg1() = 0;
        virtual bool deliverMsg2() = 0;
        bool prepareAndDeliverMsg1(){
            prepareMsg1();
            deliverMsg1();
        }
        bool prepareAndDeliverMsg2(msg2_arg1,msg2_arg2){
            prepareMsg2();
            deliverMsg2();
        }
    };
    

    您可能会发现两个派生类中的许多功能是相同的,在这种情况下,您不希望在基类中使用纯虚拟:

    class base {
        virtual bool prepareMsg1(args) {//not pure virtual
            //do the common stuff
        }
    };
    
    class derived {
        bool prepareMsg1( args ) {
            base::prepareMsg1(args);
            //code to specailise the message
        }
    };