c ++中特定重构的习语

时间:2016-10-17 08:00:42

标签: c++ polymorphism refactoring class-hierarchy

我问了这个问题:

Best Way to Refactor Class Hierarchy

以这种糟糕的方式,我在逻辑上被迫接受完全正确的答案。我的问题如下:

我有一个班级CGrandMother,其公共方法virtual bool Compute()可以

virtual bool Compute()
{
    return false;
}

来自CGrandMother的{​​{1}}公开CMother未实现Compute。现在CMother公开C1C2来实现virtual bool Compute()。现在virtual bool C1::Compute()virtual bool C2::Compute()分别为C1C2做了很多适当的事情,但也有很多相同的内容适用于CMother。现在有一个类CFamily作为成员指向CMother,并且代码Compute中几乎所有地方都通过表单行调用

ptrCMother->Compute();

我想分析与CMotherC1中完成的C2相关的常见内容,以便我不必更改所有ptrCMother->Compute();。当然,我可以在CMother中创建一个成员函数,并在bool C1::Compute()bool C2::Compute()中调用后者。但...

c++中,B来自AA::dostuff()B::dostuff()以及p是否指向某个类型{{ 1}}然后B将通过多态实现p->dostuff()。我想知道是否有一个成语/模式允许我实现这一目标:“B::dostuff()”将执行“p->dostuff()”或不执行(根据A::dostuff()让我们说)然后“ bool“,当然不会在B::dostuff()中发生非构造函数的类成员函数等。

要明确:在通过间接调用相应的派生方法之前,不会调用基本方法。是否有一个习惯用法/模式允许在相应的派生方法之前调用make(或根据c++)来生成基本方法?

1 个答案:

答案 0 :(得分:0)

您提到的解决方案有什么问题,包括在CMother类中创建一个由其子级调用的方法?

#include <iostream>
#include <memory>
using namespace std;

class CGrandMother
{
private:
    virtual bool _Compute()
    {
        return false;
    }
public:

    bool Compute()
    {
        return _Compute();
    }
};

class CMother : public CGrandMother
{
protected:
    void _CommonStuff()
    {
        cout << "work common to children" << endl;
    }
};

class C1 : public CMother
{
private:
    virtual bool _Compute() override
    {
        _CommonStuff();
        cout << "work specific to C1" << endl;

        return true;
    }
};

class C2 : public CMother
{
private:
    virtual bool _Compute() override
    {
        _CommonStuff();
        cout << "work specific to C2" << endl;

        return true;
    }
};

int main() {

    unique_ptr<CMother> c1(new C1);
    unique_ptr<CMother> c2(new C2);

    c1->Compute();
    c2->Compute();

    return 0;
}

请注意,我已经限制了我的课程的访问修饰符:

  • 遵循非虚拟接口模式,没有公共虚拟功能。公共和虚拟的功能有两个作业:它定义了一个接口和一个实现,并且往往最终都不好。
  • 方法_CommonStuff()受到保护,因此它对世界其他地方不可见但仍可由子类调用

此外,您使CMother从CGrandMother公开继承,这意味着CMother 是CGrandMother。这是真的吗?

另请注意,如果CMother是层次结构的头部,那么您可以通过其公共(但非虚拟!)Compute方法调用_CommonStuff(),并且所有子类也会自动调用_CommonStuff()。这是关于这种模式的好处之一:你可以轻松地让你的Compute()方法完成所有子类共有的工作,检查不变量等等。

看起来像这样:https://ideone.com/vXd4fL

我删除了CGrandMother,CMother现在是我的层次结构的负责人。在其公共方法Compute()中,我调用_CommonStuff()。孩子们只需要实现_Compute()。所有孩子在调用Compute()时都会自动调用_CommonStuff()。