继承或组成:依赖于“is-a”和“has-a”。 [英] Inheritance or composition: Rely on "is-a" and "has-a"?
问题描述
当我设计类并且必须在继承和组合之间选择时,我通常使用经验法则:如果关系是is-a - 使用继承,如果关系是has-a 。
When I design classes and have to choose between inheritance and composition, I usually use the rule of thumb: if the relationship is "is-a" - use inheritance, and if the relationship is "has-a" - use composition.
它总是对吗?
谢谢。
推荐答案
否 - is a不总是导致继承。一个引用良好的例子是正方形和矩形之间的关系。一个正方形是一个矩形,但设计代码继承一个Rectangle类的一个Square类将是不好的。
No - "is a" does not always lead to inheritence. A well cited example is the relationship between a square and a rectangle. A square is a rectangle, but it will be bad to design code that inherits a Square class off a Rectangle class.
我的建议是增强你的 a启发式与 Liskov替代原则。要检查继承关系是否符合Liskov替换原则,请询问基类的客户端是否可以在子类上操作,而不知道它是在子类上操作。当然,必须保留子类的所有属性。
My suggestion is to enhance your "is a / has a" heuristic with the Liskov Substitution Principle. To check whether an inheritence relationship complies with the Liskov Substitution Principle, ask whether clients of a base class can operate on the sub class without knowing that it is operating on a sub class. Of course, all the properties of the sub class must be preserved.
在正方形/矩形示例中,我们必须询问矩形的客户端是否可以在没有知道它是一个正方形。客户端必须知道的是它正在一个矩形上操作。以下函数演示了一个客户端,假设设置矩形的宽度使高度不变。
In the square / rectangle example, we must ask whether a client of rectangle can operate on a square without knowing that it is a square. All that the client must know is that it is operating on a rectangle. The following function demonstrates a client that assumes that setting the width of a rectangle leaves the height unchanged.
void g(Rectangle& r)
{
r.SetWidth(5);
r.SetHeight(4);
assert(r.GetWidth() * r.GetHeight()) == 20);
}
这个假设对于矩形是正确的,所以函数不能对平方进行操作,因此继承关系违反了Liskov替换原则。 (顺便说一句,该示例来自链接的文章。)
This assumption is true for a rectangle, but not for a square. So the function cannot operate on a square and therefore the inheritence relationship violates the Liskov Substitution principle. (By the way - the example came from the linked article.)
这篇关于继承或组成:依赖于“is-a”和“has-a”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!