Select 父 class 在运行时的实现
Select the implementation of the parent class at runtime
在一个相当大的项目中,我有一个Parent1
class,它被几个派生的class继承。我需要为父 class 的替代实现添加一个新实现。选择使用 Parent1
还是 Parent2
将在运行时完成。
一个最小的例子如下。
当前设置
class Parent1 {
void doParentStuff() {
std::cout << 0 << std::endl;
}
};
class Derived : Parent1 {
void doChildStuff() {
doParentStuff();
}
};
所需设置
现在我想添加一个新文件,其中包含 Parent2
的实现,如下所示:
class Parent2 {
void doParentStuff() {
std::cout << 1 << std::endl;
}
};
也许我创建了一个新的 Parent
class,它是 Parent1
和 Parent2
的基础 class
理想情况下,Derived class 现在看起来像这样:
class Derived : Parent {
Derived( bool whichParent ) {
// decide here whether to inherit from Parent1 or Parent2
}
void doChildStuff() {
doParentStuff(); // this will print 0 or 1, with the choice made at runtime
}
}
一个明显干净的解决方案是将设计从继承更改为组合。但是,我试图在最短的时间内完成这项工作,尽可能减少额外的代码,同时保持继承结构。这可能吗?
这是不可能的。
不过,您可以尝试这样的操作:
class SuperParent { ... };
class Parent1 : public SuperParent { ... };
class Parent2 : public SuperParent { ... };
template<class Base>
class Derived : public Base { ... };
SuperParent * derivedFactory(bool which) {
if (which) {
return new Derived<Parent1>();
} else {
return new Derived<Parent2>();
}
}
如果生成的继承层次结构允许您需要的功能。
在一个相当大的项目中,我有一个Parent1
class,它被几个派生的class继承。我需要为父 class 的替代实现添加一个新实现。选择使用 Parent1
还是 Parent2
将在运行时完成。
一个最小的例子如下。
当前设置
class Parent1 {
void doParentStuff() {
std::cout << 0 << std::endl;
}
};
class Derived : Parent1 {
void doChildStuff() {
doParentStuff();
}
};
所需设置
现在我想添加一个新文件,其中包含 Parent2
的实现,如下所示:
class Parent2 {
void doParentStuff() {
std::cout << 1 << std::endl;
}
};
也许我创建了一个新的 Parent
class,它是 Parent1
和 Parent2
理想情况下,Derived class 现在看起来像这样:
class Derived : Parent {
Derived( bool whichParent ) {
// decide here whether to inherit from Parent1 or Parent2
}
void doChildStuff() {
doParentStuff(); // this will print 0 or 1, with the choice made at runtime
}
}
一个明显干净的解决方案是将设计从继承更改为组合。但是,我试图在最短的时间内完成这项工作,尽可能减少额外的代码,同时保持继承结构。这可能吗?
这是不可能的。
不过,您可以尝试这样的操作:
class SuperParent { ... };
class Parent1 : public SuperParent { ... };
class Parent2 : public SuperParent { ... };
template<class Base>
class Derived : public Base { ... };
SuperParent * derivedFactory(bool which) {
if (which) {
return new Derived<Parent1>();
} else {
return new Derived<Parent2>();
}
}
如果生成的继承层次结构允许您需要的功能。