用c++中已有的类重构代码

Code refactoring with existing classes in C++

本文关键字:重构 代码 c++      更新时间:2023-10-16

我用c++编写代码,由于语言中没有interface关键字,所以我将在这里使用接口作为一个概念(一个契约)。

假设您有一个接口IBase,它已经由许多类实现。现在需要在接口IBase中添加另一个方法。

以最小的方式解决在所有实现类中重写该方法的问题的方法是什么?

一种方法是在Ibase类中添加带有默认实现的新方法,并让需要它的派生类覆盖它。

在上面的解决方案中,我觉得我在两个地方出错了,通过触摸界面打破了开闭原则,并且告诉用户你还可以调用另一个方法也打破了契约。

另一件让我震惊的事情是,我在基类中添加了一个方法,只有一个派生类重写了它,这基本上意味着其他类不需要那个方法。

这就引出了另一个解决方案,需要这个方法的类可以从提供这个特性的另一个类继承,或者使用组合来使用另一个类的特性。

有了上面的解决方案,我遇到了另一个问题,客户端如何通过Ibase接口访问派生类的新功能?c++中的动态分派只有在函数存在于基类中时才有效。

有人能帮帮我吗?

我只是根据下面的注释编写了我的理解,但是现在客户端代码看起来很乱,它必须知道使用哪个接口来实现额外的功能。我们应该使用factory/abstract factory抽象下面的代码吗?

#include <iostream>
using namespace std;

class IBase {
    public:
     virtual void test() = 0; 
};
class INewInterface {
    public:
     virtual void newMethod() = 0; 
};
class Derived : public IBase {
    public:
    virtual void test () {
        cout<< " Derived  " << endl;
    }
};
class DerivedSecond: public IBase, public INewInterface {
    public:
    virtual void test() {
        cout<< " Derived Second " << endl;
    }
    void newMethod( ) {
        cout<< " newMethod " << endl;
    }
};
int main( int argc, char ** argv ) {
    // Client code
    //Client needs to cast to two different interfaces to get access to the new functionality.
    // Probably should use a factory here 
    INewInterface * pNewInterfacePtr = dynamic_cast< INewInterface * > ( new DerivedSecond );
    IBase *         pIbasePtr        = dynamic_cast< IBase * > ( new DerivedSecond );
    pIbasePtr->test();
    pNewInterfacePtr->newMethod();
    return 0;
}

很难真正知道什么适合你的情况,因为你显然有一个工作系统,可能会或可能不会从我们的建议中受益。

然而,我已经生成了一个示例,说明您如何可以管理具有独立和/或重叠职责的多个子类型。这种方法是让一个容器持有所有对象的所有权,使用std::unique_ptr来确保它们都被删除,并且我们没有内存泄漏。 在添加容器中,我们为不同的视图提供了单独的容器。每个视图保存对那些具有特定职责的元素的引用(原始指针),这些元素不与其他类型共享。

也许它对你的情况有用,也许没有用。

#include <vector>
#include <memory>
#include <iostream>
class Role
{
public:
    virtual ~Role() {}
};
class RoleOne
: public virtual Role
{
public:
    virtual void do_role_one_stuff() = 0;
};
class RoleTwo
: public virtual Role
{
public:
    virtual void do_role_two_stuff() = 0;
};
class ItemA
: public RoleOne
{
public:
    void do_role_one_stuff() override { std::cout << "Item A in Role Onen"; }
};
class ItemB
: public RoleOne
, public RoleTwo
{
public:
    void do_role_one_stuff() override { std::cout << "Item B in Role Onen"; }
    void do_role_two_stuff() override { std::cout << "Item B in Role Twon"; }
};
class ItemC
: public RoleTwo
{
public:
    void do_role_two_stuff() override { std::cout << "Item C in Role Twon"; }
};
class Resources
{
    // unique_ptr ensures deletion (no memory leaks)
    std::vector<std::unique_ptr<Role>> all; // owning container
    // raw 'access' pointers share access (no need to share ownership)
    std::vector<RoleOne*> ones; // alternate 'view' (no ownership)
    std::vector<RoleTwo*> twos; // alternate 'view' (no ownership)
public:
    void add_item(Role* item)
    {
        // manage ALL items life-spans here
        all.emplace_back(item);
        // add one-centric items to the one-centric view
        if(auto one = dynamic_cast<RoleOne*>(item))
            ones.emplace_back(one);
        // add two-centric items to the two-centric view
        if(auto two = dynamic_cast<RoleTwo*>(item))
            twos.emplace_back(two);
    }
    void do_business()
    {
        // ItemA and ItemB types do this kind of business
        std::cout << "nDoing role one business:n";
        for(auto role: ones)
            role->do_role_one_stuff();
        // ItemB and ItemC types do this kind of business
        std::cout << "nDoing role two business:n";
        for(auto role: twos)
            role->do_role_two_stuff();
    }
};
int main()
{
    Resources res;
    res.add_item(new ItemA);
    res.add_item(new ItemB);
    res.add_item(new ItemC);
    res.add_item(new ItemB);
    res.add_item(new ItemA);
    res.add_item(new ItemC);
    res.do_business();
}
输出:

Doing role one business:
Item A in Role One
Item B in Role One
Item B in Role One
Item A in Role One
Doing role two business:
Item B in Role Two
Item C in Role Two
Item B in Role Two
Item C in Role Two

记住,原则不是规则。你会发现有时候你不得不打破现实世界中的一些原则,如果你明白自己在做什么,这将是一个很好的决定。然后,在IBase中创建一个新的虚拟方法可能是您的解决方案。

如果你不想破坏实际的接口,我会使用组合和委托。但我不知道你的问题。也许我的解决方案不适合你的情况。

class IBase {
public:
    virtual void test() = 0;
};
class INewIfc {
protected:
    IBase* ifc;
public:
    INewIfc(IBase* _ifc) : ifc(_ifc) {}
    ~INewIfc() {}
    virtual void newMethod() = 0;
    IBase* getIfc() {return ifc;}
}

然后从IBase(您所拥有的)创建您的具体类,或者使用IBase和新接口的组合来创建新类,而不影响以前的类。