我想创造这样一个普遍的工厂方法 - 看看这一个:问题与通用工厂方法和可变参数模板
template <class BaseType>
class Factory {
public:
template <class ... Args>
static BaseType* Create(const Args& ... args) {
return new DerivedType(args ...);
}
};
凡DerivedType
是BaseType
衍生和定义在一些其他类型不同的地方。
问题是存储DerivedType
。我想这样做,例如,像这样:
void f() {
// Derived type may have more than one constructor,
// that's why I suggest using of the variadic templates.
BaseType* ptr1 = Factory<BaseType>::Create("abc", 5, 10.);
BaseType* ptr2 = Factory<BaseType>::Create();
...
}
...
Factory<BaseType>::SetType<MyDerivedType>();
f();
Factory<BaseType>::SetType<YourDerivedType>();
f();
我可以设置不同的派生类型,但所有的人都在编译时已知的。 我想不出一个合适的技术来做到这一点。
问题:你能建议吗?
这样做的基本原理(因此,原来的问题,如果有人提出的问题是它自身的XY问题) - 是一个能力单元测试的代码中的一些棘手的部分。举例来说,如果我有一个代码:
...
Shuttle* shuttle1 = new ShuttleImpl("Discovery", Destination::Moon);
Shuttle* shuttle2 = new ShuttleImpl();
...
而且我不想每次真正构建接送我运行单元测试:
class Shuttle: public Factory<Shuttle> { ... }
...
Shuttle* shuttle1 = Shuttle::Create("Discovery", Destination::Moon);
Shuttle* shuttle2 = Shuttle::Create();
...
所以,在单元测试我可以这样做:Shuttle::SetType<TestShuttle>();
。
可能有更多的“可测试的”类,这就是为什么我需要一个通用的工厂所有的人:
class Car: public Factory<Car> { ... }
class Driver: public Factory<Driver> { ... }
...
我猜某种形式的类型擦除和模仿的'std'分配器的接口将是探索的方向,但不知道是否它实际上是可能的。 – Angew
为什么你不能使用第二个模板参数,例如:'template class Factory;'? –
CouchDeveloper
@CouchDeveloper - 因为在代码中可以有多个“Derived”:即我可以用一个完整的模拟或者一个特殊的测试类来测试相同的代码,以检查方法调用的数量。 –