如何共享特定于两个类的逻辑?
How can i share logic that is specific for two classes?
我有下一个类:WidgetBase,TextWidget,ObjectWidget,OtherWidget。TextWidget、OtherWidget 和 ObjectWidget 继承了 WidgetBase。ObjectWidget有一些逻辑,TextWidget也应该有。
class WidgetBase
{
// some base logic
}
class ObjectWidget : public WidgetBase
{
// some logic specific for ObjectWidget and TextWidget
}
class TextWidget : public WidgetBase
{
// some logic specific for ObjectWidget and TextWidget
}
class OtherWidget : public WidgetBase
{
// this class should not have logic that is specific for ObjectWidget and TextWidget
}
如何共享特定于 ObjectWidget 和 TextWidget 的逻辑? 但是,TextWidget可能没有这个逻辑。 不幸的是,装饰器和递归模板不适合这里。
一种方式是创建一个具有从WidgetBase
继承的通用逻辑的类。然后ObjectWidget
和TextWidget
都继承自此类,而不是直接从WidgetBase
继承。
如果您不希望ObjectWidget
和TextWidget
除了WidgetBase
之外还有一个共同的祖先,那么您可以使用 CRTP 模式。为此,您可以使用通用逻辑创建一个模板类。然后ObjectWidget
和TextWidget
继承自WidgetBase
和此模板类(模板参数是派生类(。
或者,模板类可以从WidgetBase
继承,然后ObjectWidget
,TextWidget
只需要从模板类继承。
简单继承应该可以帮助你 - 为 ObjWidget 和 TextWidget 引入一个通用的 util base(假设中间 doenst 需要有 Basewidget 道具(。澄清,如果这不适合 #
class WidgetBase
{
// some base logic
}
class ObjTextCommonLogic
{
public:
// Implement common logic method here
}
class ObjectWidget : public WidgetBase, protected ObjTextCommonLogic
{
// some logic specific for ObjectWidget and TextWidget
}
class TextWidget : public WidgetBase, protected ObjTextCommonLogic
{
// some logic specific for ObjectWidget and TextWidget
}
class OtherWidget : public WidgetBase
{
// this class should not have logic that is specific for ObjectWidget and TextWidget
}
不确定查询中的"逻辑"是什么意思,但您可以使用桥设计模式作为解决方案,如下所示:
struct impl {
//implementations here
void foo() { /* … */ }
void bar() { /* … */ }
};
class ObjectWidget : public WidgetBase
{
// some logic specific for ObjectWidget and TextWidget
public: void foo() { impl_->foo(); }
private: struct impl* impl_;
};
class TextWidget : public WidgetBase
{
// some logic specific for ObjectWidget and TextWidget
public: void bar() { impl_->bar(); }
private: struct impl* impl_;
};
class OtherWidget : public WidgetBase
{
// no access to struct impl
}
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 具有两个独占锁组的共享锁
- C++两个源文件之间共享的枚举的静态实例
- Directx 12 :在两个进程之间共享图形内存
- Makefile 创建两个库 - 一个依赖于另一个
- 如何使用 CMake 在 android 构建上编译和共享两个 c++ 库
- 两个单独的类不共享相同的数据 C++
- 如何共享特定于两个类的逻辑?
- 为什么我的类只适用于两个构造函数 C++
- 如何将比较运算符应用于两个匿名结构中的每个变量
- 在不使用递归的情况下将 FFT 应用于两个非常大的数字的乘法
- 在C 中,可以从第三个共享对象访问其他两个不同共享对象
- 如何区分类的两个组件共享的常用命名方法
- 如何让代码存在于两个或多个非嵌套命名空间的范围内
- 可以两个类共享一个好友功能
- 当链接到两个第三方共享库时,c++程序崩溃
- 两个进程共享同一个pcap文件
- 让两个dll共享一个静态库的缺陷是什么?
- 当函数依赖于两个不同的类时,避免进行类型检查