我想創造這樣一個普遍的工廠方法 - 看看這一個:問題與通用工廠方法和可變參數模板
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」:即我可以用一個完整的模擬或者一個特殊的測試類來測試相同的代碼,以檢查方法調用的數量。 –