用抽象基类重用对象实现多态

C++ Reusing objects to achieve Polymorphism using Abstract Base class

本文关键字:实现 多态 对象 抽象 基类      更新时间:2023-10-16

我是c++的新手,我正在研究如何在一个特定的项目中使用多态性。

我有一个组件列表。每个组件都有一个与之相关的分数,该分数是使用逻辑计算的。所以我有一个抽象类:

class Component {
    public:
        int compute_score(request *r) =0;
        int get_score() { return score; }
    protected:
        int score;
};

现在每个组件都继承这个抽象基类来实现自己的逻辑来计算组件的分数。最后的算法是将所有的Component分数合并。

// Compute and combine scores
for (int ndx = 0; ndx < num_components; ndx++) {
    total += components[ndx]->compute_score();
}
combined_score = total/num_components;

现在我正试图将这个模型适合于现有的代码库。有一个叫做request的大结构体,我想在其中添加这些Component对象并计算分数。

struct request {
    ...
    Component *components[num_components];
    ...
};
void serve(request *r) {
    ...
    // Compute and combine scores
    for (int ndx = 0; ndx < num_components; ndx++) {
        total += components->compute_score();
    }
    combined_score = total/num_components;
    ...
}
// Listener
void start(request *r) {
    // Listen for request
    // Serve the request
    serve(&r);
    // Clear the request struct for reuse
    memset(r, 0, sizeof(request)); 
} 
int main() {
    // Created only once and then reused
    request *req = (request*) calloc(1, sizeof(calloc));
    start(&req);
} 

使用组件数组的可能性:

  1. 在调用serve()时动态创建组件子类对象,并释放每次请求进入时动态分配的内存。这种方法最终会为每个请求创建对象,并可能影响性能(分配&

  2. 在请求对象内部静态地创建组件子类对象,并将它们的引用指向组件数组。我不确定这是不是一个好主意,但通过重用相同的对象解决了这个问题。我不确定如何以一种简单而优雅的方式实现这一点?

谢谢

先做最简单的解决方案

选项1 可能影响性能。这是一个很大的可能。如果我是你,我会用那个方法,因为它更简单。

如果你遇到性能问题,如果你可以证明这是分配&只有这样,你才应该考虑优化解决方案。

您最不希望看到的是不必要的复杂代码。