我遇到了这种 C++ 工厂模式,我喜欢所有权属于消费者的方式:
class MyClass {
public:
void Create(MyClass **instance, int some_param);
void Destroy(MyClass *instance);
void SomeAction() = 0;
}
// Use it
MyClass *instance;
MyClass::Create(&instance, 5);
instance->SomeAction();
MyClass::Destroy(instance);
但是你如何实施Destroy
?我想Create
看起来像:
void MyClass::Create(MyClass **instance, int some_param) {
// Subtype in some way derived from some_param
if (some_param == 1) {
*instance = (MyClass *) new MyClassSubClass();
}
// if some_param == 2, use MyDifferentSubClass() etc...
}
我已经尝试过以下类似的方法Destroy
,但无法使其正常工作:
void MyClass::Destroy(MyClass *instance) {
delete instance;
}
也许delete
需要知道特定的子类(知道它的分配大小)?但这似乎也不起作用:
void MyClass::Destroy(MyClass *instance) {
if (some_param == 1) {
delete (MyClassSubClass *)instance
}
}
非常欢迎任何输入或替代方法。