首页 > 解决方案 > 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++ 有更好的方法来处理这个问题吗?

感谢您提供的任何帮助。

标签: c++proxyduplicatespolymorphismworker

解决方案


推荐阅读