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

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

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

6.2.4 包装已有类

尽管包装遗留的结构化代码(或者甚至不可移植的代码)到一个新的(面向对象)的类中的原因比较明显,但包装已有类的需求则不那么明显。然而有很多原因来为已有(面向对象的)类创建包装对象。

软件开发人员经常使用其他人编写的代码。可能这些代码是从供应商买来的,或者是同一个组织内部其他人写的。很多情况下这些代码不能被修改。比如编写这段代码的人离职了,或者供应商不能提供维护更新等。这里就要显露出包装器的力量了。

方式是将一个现有的类包装到一个新类中,以便修改它的实现或接口。这正如我们处理结构化的代码和不可移植的代码一样。不同之处在于我们不仅建立起了面向对象的体系,而且还修改了其实现或接口。

为什么要这样做呢?答案在于实现和接口。

比如第2章中使用的数据库例子。我们的目标是为使用不同数据库的开发人员提供一致的接口。事实上,如果需要支持其他数据库,仍然要保持一致的目标,即新数据库的转换对用户来说是透明的(请见第2章图2.3)。

而且,请记得之前讨论过的关于创建中间件来为对象和关系型数据库提供一个接口。作为开发人员,我们想使用对象。因此我们想要一种将对象持久化到数据库中的功能。而我们不想为每个对象都编写SQL代码来存储到关系型数据库中。所以我们才考虑使用一个中间件来作为包装器,而我们可以使用很多支持建立对象-关系映射的产品。

从概念上来说接口和实现范式的终极案例是第2章中讨论的发电厂例子(图2.1)。在这个例子中,我们可以相互置换(包装):可以改变插线板来修改接口,亦可以改变电力生产设施来修改实现。

在软件开发过程中使用包装器是非常普遍的,不仅开发人员会大量使用,而且供应商也会使用。当开发软件系统时包装器是个很重要的工具。

在本章中,我们探究了多种设计指导。包括编写新代码以便利用以前的代码,无论已有的代码是自己的还是供应商的。某些情况下包装器甚至成为一种设计范式。比如很多情况下使用包装器作为一种设计模式。稍后我们会看到装饰器模式会包装实现,而适配器模式则修改接口。第10章会讲述更多关于设计模式的细节。 ...

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