c++ - C++ 基类作为代理
问题描述
我目前正在解决一个问题,以确定设计我的代码的最佳方式。
本质上,我有一个类,我希望它可以通过附加功能进行扩展。但是,该类的逻辑实现的具体方式取决于程序的情况(类似于策略设计模式)。
由于实现可能会有所不同,我可以设置我的基类的一系列子类,然后将另一个子类添加到这些子类中以添加我的附加功能。然而,这显然会导致大量代码重复,试图为每个实现添加逻辑。
为了解决这个问题,我尝试使用基于工作者的模型,其中基类充当工作者类的代理,允许实际的基类本身易于扩展。但是,我仍然需要编写大量代码来从本质上复制接口以指向工作程序。
我在下面提供了一个我目前正在做的事情的例子:
// Interface for workers
class Worker {
public:
virtual void x() = 0;
virtual void y() = 0;
virtual void z() = 0;
};
// This provides the actual implementation
class WorkerChild : public Worker {
public:
void x() { /*Do thing*/ }
void y() { /*Do thing*/ }
void z() { /*Do thing*/ }
};
Worker* getAppropriateWorker() {
// Some logic here to determine the appropriate type of worker to use
return nullptr; // Wouldn't actually be nullptr in practice
}
// This acts as something that is easy to instantiate and extend without
class MyClass {
private:
Worker* _worker;
public:
MyClass()
: _worker(getAppropriateWorker()) {
}
void x() { _worker->x(); }
void y() { _worker->y(); }
void z() { _worker->z(); }
};
class MyExtendedClass : public MyClass {
public:
void doAThing() {
x();
y();
}
void doAnotherThing() {
z();
y();
x();
}
};
正如你所看到的,有很多重新定义接口,MyClass 中的每个函数只是对指针进行简单的调用——逻辑没有被重复,但它仍然很慢而且很烦人。
C++ 有更好的方法来处理这个问题吗?
感谢您提供的任何帮助。
解决方案
推荐阅读
- javascript - 按下后退按钮时防止反应路由器重新加载 API 调用。反应
- yii2 - Yii CDN资产管理如何添加?
- reactjs - 在 React 中处理复杂的多层表单数据 - 复选框
- android - ColorOS 6 未知权限“读取 App-Info”
- java - JUnit 测试仅在具有 NPE 的 Jenkins 上失败
- anchor - yoloV3 中的锚框
- python - 带有验证的输入框删除数据
- amazon-ec2 - Taurus:通过 ssh 在 AWS 实例上运行 Taurus 时显示控制台屏幕故障
- image - 带有 Uint8List 的图像为空 - Flutter
- r - 页面刷新后保持动态添加的选项卡闪亮