如何设计下面的类继承

How to design the following class inheritance?

本文关键字:继承      更新时间:2023-10-16

我面临着类继承设计的问题。在c++ 中显示如下:

有两类,我们先称它们为ObjectComponentObject类使用Component类,但它们的子类出现问题。

对于simple,有6个类。

class BaseComponent{...};
class ComponentA: public BaseComponent{...};
class ComponentB: public BaseComponent{...};
class BaseObject {
public:
    virtual bool doSomething()=0;
    void setBaseComponent(BaseComponent*c){_c = c;}
    BaseComponent* getBaseComponent()   {return _c;}
private:
    BaseComponent* _c;
}
class ObjectA : public BaseObject {
public:
    bool doSomething(){ /*do someting related to ComponentA*/}
    void setComponentA(ComponentA* a)   {setBaseComponent(a);}
    ComponentA* getComponentA()         
    {return static_cast<ComponentA*>(getBaseComponent());}
}
class ObjectB : public BaseObject {
public:
    bool doSomething(){ /*do someting related to ComponentB*/}
    void setComponentB(ComponentB* b)   {setBaseComponent(b);}
    ComponentB* getComponentB()         
    {return static_cast<ComponentB*>(getBaseComponent());}
}

现在问题来了:

如果我喜欢上面的代码,我必须总是检查类关系。

(例如,当使用static_cast时,我必须检查ObjectB::getComponentB()中的真实类)

如果我更改代码并在ObjectA中直接使用ComponentA,我就放弃了"依赖倒置",这使得代码不方便。那么,谁能给我一些建议呢?

所以BaseObject的任何子类总是需要匹配的BaseComponent子类?

设置BaseObject中的setter为protected。它声称你可以给任何对象任何组件,如果除了它们之外的任何人都可以访问那个setter,那么子类就不能遵守这个承诺。

如果可能的话,将组件作为构造函数的参数会更好。

使用接口而不是具体类的想法是,当你使用接口的指针时,你不必担心后面是什么。

如果你返回具体的ComponentAComponentB,那么你失去了它。

然后,在我看来,您应该更改这些具体类,以便能够返回BaseComponent的指针,然后您将不需要static_cast。