两个子级具有相同的 F() 实现,另外两个子级具有不同的 F 实现,所有四个子级都派生自同一类
two children has same implementation of F() , other two children has different implementation of F, all four derive from same class
我有以下类层次结构。
class Base
{
virtual void F();
}
class Derived1 : public Base
{
void F() {
cout<< " one implementation"<<endl;
}
}
class Derived2 : public Base
{
void F() {
cout<< " one implementation"<<endl;
}
}
class Derived3 : public Base
{
void F() {
cout<< " other implementation"<<endl;
}
}
class Derived4 : public Base
{
void F() {
cout<< " other implementation"<<endl;
}
}
像下面这样在层次结构中引入更多类似乎可以解决问题
class Base
{
virtual void F();
}
class Base1 : public Base {
void F() {
cout<< " one implementation"<<endl;
}
}
class Base2 : public Base {
void F() {
cout<< " other implementation"<<endl;
}
}
class Derived1 : public Base1
{
}
class Derived2 : public Base1
{
}
class Derived3 : public Base2
{
}
class Derived4 : public Base2
{
}
我想知道是否可以更好地解决上述几个兄弟姐妹比其他兄弟姐妹具有相同实现的用例?我在这里缺少任何明显的设计模式吗?
如果 F 是我想要的唯一功能可能是我可以通过组合来解决它(见下文(。我不知道这样做是否是一个好主意。
组成
class Base
{
virtual void F();
}
class Base1 : public Base {
void F() {
cout<< " one implementation"<<endl;
}
}
class Base2 : public Base {
void F() {
cout<< " other implementation"<<endl;
}
}
class Derived1
{
Base * Fer;
Derived1()
{
Fer = new Base1();
}
}
class Derived2
{
Base * Fer;
Derived1()
{
Fer = new Base1();
}
}
class Derived3
{
Base * Fer;
Derived1()
{
Fer = new Base2();
}
}
class Derived4
{
Base * Fer;
Derived1()
{
Fer = new Base2();
}
}
我会使用组合,但这样:
#include <iostream>
// define an interface
class Base
{
virtual void F() = 0;
};
// define an implementation framework which pulls in templated
// components to do the work
template<class HandleF>
struct Impl : Base
{
virtual void F() override {
f_handler(this);
}
HandleF f_handler;
};
struct OneImplementationOfF
{
template<class Self>
void operator()(Self* self) const
{
std::cout<< " one implementation"<< std::endl;
}
};
struct OtherImplementationOfF
{
template<class Self>
void operator()(Self* self) const
{
std::cout<< " other implementation"<< std::endl;
}
};
// now build our classes
class Derived1 : public Impl<OneImplementationOfF>
{
};
class Derived2 : public Impl<OneImplementationOfF>
{
};
class Derived3 : public Impl<OtherImplementationOfF>
{
};
class Derived4 : public Impl<OtherImplementationOfF>
{
};
相关文章:
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- C++哈希表中,两个相同的实现,但一个给出错误
- 如何将这两个函数组合成一个实现?
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- std::list 的两个 insert() 方法签名之间的实现差异
- 为什么<T> LLVM 中的预期为 Expect&&... 实现两个构造函数<T>?
- 为什么我们不能同时实现两个方法'getAB() &&'和'getAB()'?
- 在C++中实现两个大小相等的排序数组的中位数
- 模板化成员函数能否实现两个基类的虚函数?
- 如何使用C 中的共享/弱指针清洁实现两个对象
- 如何实现两个类以自动决定深层和浅层复制
- C++堆栈实现 - 两个版本的 top 方法
- 实现两个名称相同但由于多个抽象基类而不同的非协变返回类型的函数
- 快速实现两个 8 位数组的协方差
- 如何用C++在同一窗体中实现两个相同的OpenGL UserControl
- 我如何在c++的一个类中实现两个同名的函数
- 通过实现两个不同于const的函数来避免代码重复
- 如何实现两个可以相互访问的结构体
- 如何实现两个线程的并发
- 用C++实现两个类层次结构的双重调度