Design principle--multiple use of combination and less use of inheritance

for example:

We know that both rice and bean paste are (inherited) foods, then we wrap the bean paste with rice and steam it in a pot, and we get (derived) zongzi.
Such a structure is:
    food
    /\
rice bean paste
    \/
     zongzi
This is a diamond shape, so it is called a diamond problem: If there is a member of the "taste" in the food, which one does the "taste" of the zongzi inherit from? ?
In C++, a language that supports multiple inheritance, if you use it directly 

Zongzi Zongzi a;
cout  << Zongzi a. Deliciousness<< endl;


Then you will find that the compiler (g++) reports an error: the request for the "taste" of the member is ambiguous.
Fortunately, there are 3 solutions:
1. Redefine a deliciousness to cover the deliciousness of rice and bean paste.
2. Indicate which parent class is delicious: for example Zongzi a.Rice::Delicacy or Zongzia.Bean paste::Delicacy3
. Use virtual inheritance (virtual base class), see STFW for details.

 

So I suddenly thought that if the design principle of "use more composition, less inheritance" is used here (much like solution 2), then the problem will be solved:

class 粽子: public 食品{
private:
    米饭 米饭a;
    豆沙 豆沙a;
public:
    粽子(){
        好吃程度 = (米饭a.好吃程度 + 豆沙a.好吃程度) / 2; //其实我觉得豆沙a的权值应该大些=.=
    }
};

 

这个哥的UML图也能让我们很好理解:

http://www.cnblogs.com/bluedy1229/archive/2008/11/19/1286692.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326409843&siteId=291194637