【发布时间】:2014-07-17 07:49:32
【问题描述】:
我将某些功能封装在其他类中使用的类中。我觉得这叫作曲。
class DoesSomething01
{
public:
DoesSomething01();
void functionality01();
void functionality02();
};
class DoesSomething02
{
public:
DoesSomething02();
void functionality01();
void functionality02();
};
class ClassA
{
public:
ClassA();
private:
DoesSomething01 *m_doesSomething01;
DoesSomething02 *m_doesSomething02;
};
如果我现在有一个“知道”ClassA 的ClassB 并且必须使用/执行functionality01 和/或functionality02 类DoesSomething01 和/或DoesSomething02 我看到两种可能性:
a) 将这样的方法添加到ClassA 以提供ClassB 对DoesSomething01 和/或DoesSomething02 的直接访问:
DoesSomething01 *getDoesSomething01() { return *m_doesSomething01; }
DoesSomething02 *getDoesSomething02() { return *m_doesSomething02; }
ClassB 可以这样做:
m_classA->getDoesSomething01()->functionality01();
b) 将(在本例中为四个)方法添加到 ClassA,它将方法调用转发到 DoesSomething01 和 DoesSomething02,如下所示:
void doesSomething01Functionality01() { m_doesSomething01->functionality01(); }
void doesSomething01Functionality02() { m_doesSomething01->functionality02(); }
void doesSomething02Functionality01() { m_doesSomething02->functionality01(); }
void doesSomething02Functionality02() { m_doesSomething02->functionality02(); }
哪个选项更好,为什么?
每个选项的优点/缺点是什么?
【问题讨论】:
-
getDoesSomthing01()和getDoesSomthing02()必须/应该返回一个指针:DoesSomthing01* getDoesSomthing01() { return m_doesSomthing01; } -
当然,你是对的。
标签: c++ design-patterns architecture composition