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

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

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

7.1 重用对象

继承和组合的主要目的大概就是对象重用。简单来说,通过继承和组合来利用其他类就可以构建新的类(其最终变为对象)。实际上这是重用以前构建好的类的唯一方式。

继承代表了is-a关系。第1章中介绍过该关系。比如,狗是哺乳动物。

组合则是使用其他类来构建出更加复杂的类,即一个装配集合。这种情况下没有父子关系。基本上复杂的对象都是由其他对象组合而成的。组合代表了has-a关系。例如,汽车拥有一个引擎。引擎和汽车是分离的、独立的对象。然而,汽车是一个复杂的对象,包含(有)引擎对象。事实上,子对象本身也有可能由其他对象组成。比如,引擎包括气缸。即引擎拥有一个(实际上有多个)气缸。

当面向对象的技术刚成为主流时,继承往往是设计一个面向对象系统的第一个示例。你会先设计一个类,然后继承它的功能,这是使用面向对象技术的最突出的优势之一。重用是目的,而继承则是重用的终极表示。

但是随着时间的推移,继承的光环逐渐褪去。事实上有些讨论中使用继承本身就令人疑惑。在Peter Coad和Mark Mayfield撰写的Java Design一书中有一章标题为“使用组合而不是继承来进行设计”。很多早期的基于对象的平台甚至并不真正支持继承。当Visual Basic演化到Visual Basic .NET时,早期的基于对象的实现并不具有严格的继承能力。诸如MS COM模型等平台都是基于接口继承。第8章将讲述接口继承的细节。

如今对继承的使用仍然是充满争议的主题。抽象类是一种继承方式,很多语言并不直接支持此特性,比如Objective-C和Swift。即使接口提供不了抽象类的全部功能,我们还是会使用接口。

好消息是关于是使用继承还是组合的争论逐渐变得理性。正如所有明智的质疑一样,两方都有充满激情的观点。幸运的是,往往这些讨论能帮助我们更加清晰地理解如何优化该技术。 ...

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