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

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

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

2.2 使用抽象思维设计接口

面向对象编程的主要优势之一是可以重用类。通常可以重用的类比具体的类的接口更加抽象。具体的接口可以是非常明确的,而抽象接口则更通用。简单来说高层次的抽象接口比高度具体的接口更有用,大部分情况下如此,当然并非适用于所有情况。

完全可以编写一个非常有用的具体的类,而且这个类无法被重用。这种情况经常出现,在某些情况下它也没什么错。然而,我们需要进行业务设计时能得到面向对象提供的优势。所以我们的目标是设计抽象的可高度重用的类。为了做到这一点,需要设计高度抽象的用户接口。我们可以创建一个出租车对象来演示抽象接口与具体接口的区别。该对象拥有一个诸如“把我载到机场”接口可能比拥有一些独立的诸如“左转”“右转”“启动”“停止”之类的接口更有用。因为正如图2.4所示,用户只想去机场。

当你从酒店出来,把行李放到出租车后备厢,并坐上出租车,出租车司机会问你:“你想去哪里?”你回答:“请送我到机场。”(当然这里假设这个城市只有一个机场。在芝加哥,你可能会说,“请送我到Midway机场”或“请送我到O’Hare机场”。)你可能自己都不知道如何到机场,或者即使你知道,你也无须告诉司机什么时候转弯,转到哪个方向。如图2.5展示了出租车司机的实际驾驶路径,而作为乘客的你无须关心(然而,如果司机绕路欺骗你去机场,费用可能会有点问题)。

图2.4 抽象接口

图2.5 一个具体的接口

现在,抽象和重用的联系在哪里?请你自问这两个场景哪个更具重用性,是抽象的还是非抽象的?我们来更进一步简化问题,以下哪个短语更具重用性?是“送我到机场”还是“右转,右转,然后再左转,左转,左转”。显而易见,第一个短语更具重用性。你可以在任何城市中使用它,只要你钻进一辆出租车并且想去机场。第二个短语只在特定的情况下可行。因此,抽象接口“带我去机场”更具通用性。可重用的面向对象设计针对芝加哥、纽约或克利夫兰的实现是不同的。 ...

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