如何共享特定于两个类的逻辑?

How can i share logic that is specific for two classes?

本文关键字:于两个 何共享 共享      更新时间:2023-10-16

我有下一个类: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继承的通用逻辑的类。然后ObjectWidgetTextWidget都继承自此类,而不是直接从WidgetBase继承。

如果您不希望ObjectWidgetTextWidget除了WidgetBase之外还有一个共同的祖先,那么您可以使用 CRTP 模式。为此,您可以使用通用逻辑创建一个模板类。然后ObjectWidgetTextWidget继承自WidgetBase和此模板类(模板参数是派生类(。

或者,模板类可以从WidgetBase继承,然后ObjectWidgetTextWidget只需要从模板类继承。

简单继承应该可以帮助你 - 为 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    
}