我想创建一个可以使用四种算法之一的类(并且要使用的算法仅在运行时才知道)。我在想策略设计模式听起来很合适,但我的问题是每个算法都需要稍微不同的参数。使用策略,但将相关参数传递给构造函数,会不会是一个糟糕的设计?
这是一个示例(为简单起见,假设只有两种可能的算法)...
class Foo
{
private:
// At run-time the correct algorithm is used, e.g. a = new Algorithm1(1);
AlgorithmInterface* a;
};
class AlgorithmInterface
{
public:
virtual void DoSomething() = 0;
};
class Algorithm1 : public AlgorithmInterface
{
public:
Algorithm1( int i ) : value(i) {}
virtual void DoSomething(){ // Does something with int value };
int value;
};
class Algorithm2 : public AlgorithmInterface
{
public:
Algorithm2( bool b ) : value(b) {}
virtual void DoSomething(){ // Do something with bool value };
bool value;
};