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

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

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

11.1.2 组合

与其把行为嵌入类本身,我们给每个行为创建单独的类。因此,相比把行为放置在继承的层级中,我们创建单独的哺乳动物类,并在类里面(通过聚合)包含所需的行为。

我们创建一个类叫作Walkable,一个类叫作Flyable,如图11.2所示。

从下面的代码里面我们能看到,类Mammal与eat()方法在一起,而Dog、Cat仍然存在,但是主要的设计区别在于这些类通过使用组合的聚合得到了行为。

小心

前面段落里提到的聚合这个词需要好好理解。这个例子只是说明如何用组合取代继承。然而,在示例中,我们是用聚合方式实现的,这种方式仍然有很多的耦合。这里只是一个过渡性的说明,下一个例子我们会使用接口来实现。

图11.2 使用组合创建哺乳动物类

注意

这个例子的意图在于说明如何使用组合代替继承,但这并不意味着在所有的设计中都不能使用继承。举个例子,如果你判断所有的哺乳动物类都需要进食,那么你可以把eat()这个方法放入Mammal类,让Dog和Bat继承于Mammal。这只不过是设计方案的选择而已。

本章讨论的关键在于继承会破坏封装。这一点很容易理解,当Mammal类发生变化的时候,所有的子类都需要重新编译甚至重新部署。这意味着这些类都是高度耦合的,违背了我们希望尽量解耦类的初衷。

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