c++ 类设计、基类继承或门面设计模式

标签 c++ c++11 inheritance facade

我有一个愚蠢的 C++ 设计问题。有没有一种方法可以让一个类与多个类中的方法具有相同的方法名称(因此,具有相同的 API)?

我现在的情况是有课的情况

struct A
{
    void foo() { std::cout << "A::foo" << std::endl;}
    void boo() { std::cout << "A::boo" << std::endl;}
};

struct B
{
    void moo() { std::cout << "B::moo" << std::endl;}
    void goo() { std::cout << "A::goo" << std::endl;}
};
.... imagine possibly more

我真正想要的是另一个类,它充当这些功能的接口(interface)。我可能会误解为一个简单接口(interface)的外观设计模式,它隐藏了上面实例化类的复杂性,但仍然使用它们相同的接口(interface)。

struct C 
{
    void foo() { ... }
    void boo() { ... }
    void moo() { ... }
    void goo() { ... }
};

对于上面显示的少量方法,这可以通过声明结构 A 和 B 或将它们作为参数传递给结构 C 并在 C 中调用 A 和 B 的方法来实现,但如果 A 有 40 个方法而 B 则这是不切实际的有30个方法。如果我能做得更好的话,在 C 中重新声明 70 个同名方法来调用 A 和 B 的底层方法似乎是无缘无故的大量冗余。

我想到了使用基类的第二种解决方案

struct base
{
    void foo() { }
    void boo() { }

    void moo() { }
    void goo() { }
};

struct A : public base
{
    void foo() { std::cout << "A::foo" << std::endl;}
    void boo() { std::cout << "A::boo" << std::endl;}
};

struct B : public base
{
    void moo() { std::cout << "B::moo" << std::endl;}
    void goo() { std::cout << "A::goo" << std::endl;}
};

尝试使用具有所有函数定义的 shared_ptr。例如

std::shared_ptr<base> l_var;
l_var->foo();
l_var->boo();
l_var->moo();
l_var->goo();

这仍然不能完全满足我的要求,因为一半的方法是在结构 A 中定义的,而另一半是在结构 B 中定义的。

我想知道多重继承是否可以解决问题,但在学校我听说进行多重继承是不好的做法(调试很难?)

有什么想法或建议吗?基本上,管理结构 A 和 B 更容易(等等,因为它是出于抽象目的的自己的类)。但是希望在某种包装器中以某种方式调用他们的方法的灵 active ,其中这种复杂性对用户隐藏。

最佳答案

我认为

Redeclaring 70 methods with the same name in C to call the underlying methods of A and B

正确的路径。

在这种情况下很容易使用多重继承来避免编写传递代码,但我认为这通常是一个错误。优先使用组合而不是继承。

我会质疑您的用户是否真的想用 70 种方法处理一个接口(interface),但如果那真的是您想要的,那么我不明白为什么在 C 中编写代码是“不切实际的” :

class C {
    A a;
    B b;
public:
    void foo() { return a.foo(); }
    void boo() { return a.boo(); }
    void moo() { return b.moo(); }
    void goo() { return b.goo(); }
    // ...
};

Live demo .

这样做的好处是您以后可以轻松改变主意并替换AB在不更改 C 界面的情况下使用其他东西.

您可以隐藏 C 的实现进一步 using PIMPL 习语或 splitting C进入抽象基类C和一个实现 CImpl .

关于c++ 类设计、基类继承或门面设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50312460/

相关文章:

C++ Lambda 导致 'candidate function not viable:'

c++ - 文档{}的mongodb C++驱动程序编译错误

c++ - 为什么我必须通过this指针访问模板基类成员?

c++ - 类继承 : Constructor and member functions of class not recognized by compiler

c++ - 无法让我的 C++ 程序显示输出

c++ - 仅当集合为空时才弹出值的直觉

c++ - 可变模板的部分特化需要第一个非可变模板参数

c++ - 如何使用正则表达式和 boost 变换迭代器标记和变换 c 字符串?

python - TypeError: object.__new__() 使用继承时不带参数

java - Java中的基本多态性/将父类(super class)转换为子类