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

Inheritance or composition: Rely on quot;is-aquot; and quot;has-aquot;?(继承或组合:依赖“is-a和“有?)
本文介绍了继承或组合:依赖“is-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.

总是对的吗?

谢谢.

推荐答案

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

其他示例

这篇关于继承或组合:依赖“is-a"和“有"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)