Mew*_*zer 6 c++ inheritance design-patterns strategy-pattern code-design
我想创建一个可以使用四种算法之一的类(并且使用的算法仅在运行时才知道).我认为策略设计模式听起来合适,但我的问题是每个算法需要稍微不同的参数.使用策略是一个糟糕的设计,但是将相关参数传递给构造函数?
这是一个例子(为简单起见,假设只有两种可能的算法)......
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;
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
453 次 |
最近记录: |