继承或组合:依赖“is-a"和“有"?

2021-12-12 00:00:00 oop inheritance c++

当我设计类并且不得不在继承和组合之间做出选择时,我通常使用经验法则:如果关系是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.

总是对的吗?

谢谢.

推荐答案

否 - 是一个"并不总是导致继承.一个很好引用的例子是正方形和长方形之间的关系.正方形是长方形,但设计代码从 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.

我的建议是使用 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);
}

这个假设适用于矩形,但不适用于正方形.因此该函数不能对正方形进行操作,因此继承关系违反了里氏替换原则.

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.

其他示例

相关文章