我想知道是否存在一种设计模式,用于指定一组算法的选项。我正在使用C++。
让我描述一下我的问题。我有一组算法,这些算法有不同的选择。我想设计对这些算法的单点访问。类似于策略模式。这种单点访问是一个 Controller 类,它将输入作为通用选项类。根据选项,将使用合适的算法。我想归纳这些选项,以便我可以扩展算法和客户端。
谢谢,
阿莫尔
最佳答案
在Konrad's suggestion of using policy types上构建,如果您的算法在构造时需要参数,则可以通过要求任何Policy
类具有称为Params
的嵌套类型,然后在fancy_algorithm<Policy>
内部提供构造函数,以采用此类型的参数并将其传递给包含的Policy
对象:
template <typename Policy>
class fancy_algorithm : private Policy {
public:
typedef typename Policy::Params Params; // Need to redeclare :(
explicit fancy_algorithm(Params params = Params()) : Policy(params) {}
};
任何相关参数都需要打包到
Policy::Params
类型的单个对象中。Policy
类始终使用Policy::Params
类型的单个参数构造。要使用(可能)不需要参数的策略类,请在Params
而不是Policy
中提供默认构造函数(或使用隐式声明的构造函数)。这样,通过使用上述fancy_algorithm<Policy>
构造函数的默认值,只要fancy_algorithm<Policy>
具有默认构造函数(即Policy::Params
不需要任何参数),我们就可以方便地对Policy
进行默认构造。没有任何安全损失:如果Policy::Params
缺少默认构造函数(表明某些参数是必需的),则任何默认构造fancy_algorithm<Policy>
对象的尝试都将在编译时失败。例子:
struct multiply_by_params {
multiply_by_params(int x /* = 42 */) : _x(x) {} // See bottom
int get() const { return _x; } // Or, just make multiply_by a friend
private:
int _x;
};
struct multiply_by {
typedef multiply_by_params Params;
multiply_by(Params p) : _x(p.get()) { /* Other initialisation */ }
// Other code implementing the strategy (e.g. an operator()())
...
private:
int _x;
};
fancy_algorithm<multiply_by> a(69); // Always compiles
fancy_algorithm<multiply_by> b; // Compiles iff /* = 42 */ is uncommented