设计算法的通用选项

Amo*_*wai 3 c++ design-patterns

我想知道是否有用于为一组算法指定选项的设计模式.我正在使用C++.让我来描述我的问题.我有一套算法,这些算法有不同的选择.我想设计一个单点访问这些算法.类似于策略模式的东西.此单点访问是一个控制器类,它将输入作为通用选项类.根据选项,将使用合适的算法.我想概括这些选项,以便我可以扩展算法和客户端.谢谢,Amol

Kon*_*lph 7

一个经常使用的模式是创建一个策略类,它作为模板类型传递给您的类,然后从私有继承:

template <typename Policy>
class fancy_algorithm : private Policy {
};
Run Code Online (Sandbox Code Playgroud)

一个着名的例子std::allocator是通常以这种方式继承的类:

template <typename T, typename Alloc = std::allocator<T> >
class my_container : private Alloc {
public:
    typedef Alloc allocator;

    // It's necessary to make the base class names available explicitly.
    typedef typename allocator::pointer pointer;

    using allocator::construct;
    // …
};
Run Code Online (Sandbox Code Playgroud)