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

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

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

8.3.1 抽象类

实现契约的方式之一是使用抽象类。抽象类包含一个或多个没有提供任何实现的方法。假设有一个名为Shape的抽象类,这个类是抽象的,因为你无法实例化它。如果你让某人绘制形状,这个人首先会问你“绘制哪种形状?”因此,形状这个概念是抽象的。然而如果某人让你绘制一个圆,你就不会问这个问题,因为圆是一个实体概念,你知道圆形是什么样子的。你也知道如何绘制诸如矩形等其他形状。

如何应用契约?假设我们想创建一个应用程序来绘制形状。我们的目标是绘制当前设计中包含的所有类型的形状,以后还可以添加新的形状。那么必须遵循两个条件:

首先,所有形状必须使用相同的语法来绘制自身。例如,在自定义的系统中每个形状都包含一个名为draw()的方法。因此经验丰富的开发人员无须知晓具体的形状,只需调用draw()方法就可以绘制形状。从理论上来说这减少了查看API文档的时间,而且避免了语法错误。

其次,请记住每个类必须要响应自身的行为。因此一个类被要求提供一个draw()的方法,还必须提供该代码的具体实现。例如,Circle类和Rectangle类都有draw()方法,而Circle类拥有绘制圆形的代码,而Rectangle类有绘制矩形的代码。当最终创建Circle和Rectangle类时,它们都是Shape的子类,这些类必须实现各自的Draw的版本(如图8.3所示)。

图8.3 抽象类继承体系图

抽象方法

在UML类图中,抽象方法是斜体的。

这样Shape框架拥有多态性。系统中的单个对象都可以调用Draw方法,调用不同的形状会返回不同的结果。调用Circle对象中的Draw方法会绘制一个圆,调用Rectangle对象中的Draw方法会绘制一个矩形。本质上,向对象发送消息,不同的对象会得到不同的响应。这是多态性的本质: ...

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