gpt4 book ai didi

c++ - 哪种设计模式最合适?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:15:17 25 4
gpt4 key购买 nike

我想创建一个可以使用四种算法之一的类(并且要使用的算法仅在运行时已知)。我当时认为 Strategy 设计模式听起来很合适,但我的问题是每个算法需要的参数略有不同。使用策略,但将相关参数传递给构造函数是否是一个糟糕的设计?。

这是一个例子(为简单起见,假设只有两种可能的算法)...

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

最佳答案

这将是一个有效的设计,因为 Strategy 模式要求定义一个接口(interface),并且任何实现它的类都是运行策略代码的有效候选者,无论它是如何构建的。

关于c++ - 哪种设计模式最合适?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2961431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com