您可以使用Factory Pattern 以及Strategy Pattern 和适当的接口。类似的东西:
struct IPolyRootSolver {
virtual PolyRoot calcRoot(const Polynom& poly) const = 0;
virtual ~IPolyRootSolver () {}
};
class DoublePolyRootSolver : public IPolyRootSolver {
public:
PolyRoot calcRoot(const Polynom& poly) {
// Implementation based on double precision
}
};
class LongDoublePolyRootSolver : public IPolyRootSolver {
public:
PolyRoot calcRoot(const Polynom& poly) {
// Implementation based on long double precision
}
};
class MPFRCPolyRootSolver : public IPolyRootSolver {
public:
PolyRoot calcRoot(const Polynom& poly) {
// Implementation based on MPFRC++ precision
}
};
class RootSolverFactory {
public:
RootSolverFactory(const std::string configFile) {
// Read config file and install a mechanism to watch for changes
}
std::unique_ptr<IPolyRootSolver> getConfiguredPolyRootSolver() {
if(config file contains type = double) {
return make_unique<IPolyRootSolver>(new DoublePolyRootSolver());
}
else if(config file contains type = long double) {
return make_unique<IPolyRootSolver>(new LongDoublePolyRootSolver());
}
else if(config file contains type = MPFRC) {
return make_unique<IPolyRootSolver>(new MPFRCPolyRootSolver ());
}
else {
// Handle the default case
}
};
我希望你明白我的意思。
如 cmets 中所述,您还可以使用命名空间中的独立函数,而不是上面提到的抽象接口解决方案:
namespace PolyRootDoublePrecision {
PolyRoot calcRoot(const Polynom&);
}
namespace PolyRootLongDoublePrecision {
PolyRoot calcRoot(const Polynom&);
}
namespace PolyRootMPFRCPrecision {
PolyRoot calcRoot(const Polynom&);
}
class RootSolverFactory {
public:
RootSolverFactory(const std::string configFile) {
// Read config file and install a mechanism to watch for changes
}
std::function<PolyRoot (const Polynom&)> getConfiguredPolyRootSolver() {
if(config file contains type = double) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootDoublePrecision::calcRoot);
}
else if(config file contains type = long double) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootLongDoublePrecision::calcRoot);
}
else if(config file contains type = MPFRC) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootMPFRCPrecision::calcRoot);
}
else {
// Handle the default case
}
};
除了使用配置文件之外,您还可以考虑从其他条件中选择要使用的策略作为配置文件。
例如对于您的情况,多项式表达式的复杂性(即子项的数量)似乎对于选择要使用的最佳策略起着至关重要的作用。所以你可以写一些类似的代码
std::function<PolyRoot (const Polynom&)> getPolyRootSolver(const Polynom& polynom) {
if(polynom.complexity() < 7) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootDoublePrecision::calcRoot);
}
else if(polynom.complexity() >= 7 &&
polynom.complexity() < 50) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootLongDoublePrecision::calcRoot);
}
else if(polynom.complexity() >= 50) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootMPFRCPrecision::calcRoot);
}
};