tags:

views:

173

answers:

4

class A was using below two functions to build and send messages 1 & 2

builder::prepareAndDeliverMsg1(msg1_arg1,msg1_arg2)
{
}

builder::prepareAndDeliverMsg2(msg2_arg1,msg2_arg2)
{
}

Now, a new class B is introduced, which would like to do what A was doing in two stages

stage1->prepare stage2->deliver

I was thinking to extend the builder class like below:

///----

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)
{
}

//---

I would like to know, if there is any better way of designing this ?

+2  A: 

Your solution looks ok to me.

MiniQuark
+3  A: 

maybe for each message, create your own class and inherit from the base message class?

class TBaseMsg
{
public:
   virtual void prepare() = 0;
   virtual void deliver() = 0;
}
dark
+2  A: 

You can take a look at Decorator design pattern.

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

Mykola Golubyev
+1  A: 

To expand on Darks idea you can have a base class that implements the combined prepare and delivers in terms of the separate functions and allows deriving classes to override those as required:

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();
    }
};

You may find that a lot of the functionality from the two derived classes is the same in which case you won't want to use pure virtuals in the base class:

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

It could even be that the base class implments your original class but allows your second class to be derived without having to repeat the common code.

Patrick
Thanks Patrick, though your solution requires a re-write of the existing code.I would like to do it for more neater solution. The fellow who had written the existing C++ codem , used more C than C++....
Warrior
Remember to always define a virtual destructor in a class that has (or derives from a class that has) at least one virtual function. Or else you may be surprised to see that your derived class's destructor is not called in some cases.
MiniQuark