读书笔记之组合
若是逻辑上A是B的“一部分”(a part of),则不允许B从A派生,而是要用A和其他东西组合出B。
例如眼、鼻、口、耳是头的一部分,所以类Head应该由类Eye、Nose、Mouth、Ear组合而成,而不是派生而成。程序如下:
class Eye
{
public:
void Look();
};
class Nose
{
public:
void Smell();
};
class Mouth
{
public:
void Eat();
};
class Ear
{
public:
void Listen();
};
class Head
{
public:
void Look(){m_eye.Look();}
void Smell(){m_nose.Smell();}
void Eat(){m_mouth.Eat();}
void Listen(){m_ear.Listen();}
private:
Eye m_eye;
Nose m_nose;
Mouth m_mouth;
Ear m_ear;
};
{
public:
void Look();
};
class Nose
{
public:
void Smell();
};
class Mouth
{
public:
void Eat();
};
class Ear
{
public:
void Listen();
};
class Head
{
public:
void Look(){m_eye.Look();}
void Smell(){m_nose.Smell();}
void Eat(){m_mouth.Eat();}
void Listen(){m_ear.Listen();}
private:
Eye m_eye;
Nose m_nose;
Mouth m_mouth;
Ear m_ear;
};
Head由Eye、Nose、Mouth、Ear组合而成。如果允许Head从Eye、Nose、Mouth、Ear派生而成,那么Head将自动具有Look、Smell、Eat、Listen这些功能。程序十分简短并且运行正确,但是下面这种设计方法却是不对的。
class Head:public Eye,public Nose,public Mouth,public Ear
{
};
{
};