Flexible class behavior in C++
I need to write a class 开发者_如何学编程in C++ that would represent an abstraction of a calculation. That class will have a function that will run an actual calculation.
class Calculation {
Calculation() {}
~Calculation() {}
Calculate(); //member function that runs a calculation
};
I need that class to be able to represent different sorts of calculations and run different calculation as the result of calling Calculation::Calculate()
. What are some good approaches to do this in C++? I could do that just passing some flags into constructor, but this doesn't seem to be a good solution.
You can make Calculate
virtual and create child classes that implement the varying behavior you need.
How about an object-oriented design?
class Calculation
{
Calculation();
public:
virtual ~Calculation() {}
virtual int Calculate() = 0;
};
class Sum : public Calculation
{
int x, y;
public:
Sum(int x_, int y_) : x(x_), y(y_) {}
~Sum() {}
virtual int Calculate() { return x + y; }
};
You should look into the Command Design Pattern. It is often used to implement "undo" operations in GUI systems but is well suited to other situations where you need to postpone the moment where the actual operation is performed.
C++ implementations typically resort to an abstract class (interface) with a single abstract method with no arguments, then implementing this interface for each operation. The arguments for the computation are bound in the derived class' constructor. Then, instances of your abstract class are queue in some fashion. When it's time to execute the action, just invoke the generic, no-argument method is called.
精彩评论