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

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

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

7.4.1 继承如何减弱封装

之前已经提过,封装就是把类打包为公共接口和私有实现的过程。本质来说一个类应该隐藏其他类无须了解的任何事情。

Peter Coad和Mark Mayfield在使用继承时举了一个例子,在类的体系结构中封装弱化了封装。他们讨论了一个具体的风险,继承意味着对其他类的强封装,但是弱化了父类和其子类之间的封装。

如果你从父类中继承一个实现,然后父类修改了这个实现,父类的修改会波及整个类的体系结构。这种波及潜在影响所有的子类。貌似这看起来不是一个大问题。但是,正如我们看到的一样,这种波及影响会导致难以预料的问题。例如,测试会变成噩梦。第6章中我们讨论了使用封装会更加容易测试系统。理论上来说,如果创建了一个名为Cabbie的类(如图7.9),使用了相应的公共接口,那么任何对于Cabbile类的实现修改对于其他类来说都是透明的。然而,任何设计中,父类的修改对子类来说都是不透明的。这是一个难题。

如果其他类直接依赖于Cabbie类的实现,测试则会变得更加困难。通过使用不同的设计方式,通过提取行为,只继承属性,以上的问题都迎刃而解。

图7.9 Cabbie类的UML图

持续测试

即使使用封装,你依然想重测使用了Cabbie类的类来验证本次修改没有引入任何问题。

如果创建了一个Cabbie类的子类,叫作PartTimeCabbie,PartTimeCabbie继承了Cabbie的实现,那么修改Cabbie的实现会直接影响到PartTimeCabbie类。

请看图7.10中的示例,PartTimeCabbie是Cabbie的子类。因此,PartTime-Cabbie继承了Cabbie的公共实现,包括方法giveDirections()。如果Cabbie中的giveDirections()发生了改变,它将会直接影响PartTimeCabbie类,以及其他可能成为Cabbie子类的类。在这种微妙的情形下,对Cabbie实现的修改没必要封装到Cabbie类中。 ...

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

桑德.范.乌格特
Java并发编程实战

Java并发编程实战

Brian Goetz, Tim Peierls

Publisher Resources

ISBN: 9787111684527