Skip to Content
面向对象的思考过程(原书第5版)
book

面向对象的思考过程(原书第5版)

by 马特 魏斯费尔德
August 2021
Intermediate to advanced
450 pages
4h 46m
Chinese
Pearson
Content preview from 面向对象的思考过程(原书第5版)

7.3 组合

一个对象包含其他的对象是很自然的。电视机包括按钮和显示器。计算机包含显卡、键盘以及驱动。计算机可以看作一个代表自身的对象,而闪存驱动也是一个有效的对象。你可以拆开电脑把硬盘除移下来并拿到手上。实际上你可以把这块硬盘安装到其他电脑上。硬盘是一个独立的对象,因为它可以在不同的计算机上工作。

对象组合的经典例子是汽车。很多书、培训课程以及文章中都使用汽车作为对象组合的经典示例。除了步枪制作流水线外,大多数人认为Henry Ford创造的汽车装配流水线是可替换部件的经典例子。因此汽车自然成为设计面向对象软件系统时的主要引用示例。

大多数人认为汽车包含引擎是很自然的事情。然而汽车除了引擎还包括其他对象,比如轮子、方向盘以及立体音响系统。一个特定的对象由其他对象组合而成,而且这些对象包含在对象字段中,那么这个新的对象被称为混合(或者聚合,或者综合)对象(如图7.6所示)。

聚合、联合以及组合

在我看来重用类只有两种方式,继承和组合。第9章中我们将讨论组合的更多细节,具体来说就是聚合和联合。尽管大家对聚合和联合有多种观点,但在本书中我认为聚合和联合是组合的方式。

图7.6 组合示例

使用UML表示组合

UML使用图7.7中的标记来模型化展示汽车对象包含一个方向盘对象这一事实。

聚合、联合以及UML

本书中,UML中的聚合以带线的菱形表示,比如引擎是汽车的一部分。联合则只由一根线(没有菱形)表示,比如独立的键盘服务于一台单独的计算机。

图7.7 使用UML表示组合

注意连接Car类和SteeringWheel类的连线在Car类这一端带有一个菱形。这表示了汽车包含(has-a)方向盘。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Node与Express开发(第2版)

Node与Express开发(第2版)

Ethan Brown
计算机科学导论:跨学科方法

计算机科学导论:跨学科方法

罗伯特 塞奇威克, 凯文 韦恩
手把手教会你linux

手把手教会你linux

桑德.范.乌格特
Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉

Publisher Resources

ISBN: 9787111684527