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

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

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

8.3.5 创建契约

定义契约的简单规则就是通过抽象类或接口提供一个不含实现的方法。因此,设计遵守契约的子类时,它必须提供父类(或接口)中对不包含实现的方法的实现。

之前提到过,契约的优势之一是标准化编码的约定。我们可以通过一个没有采用编码标准的示例来详细探讨这个概念。有三个类:Planet、Car和Dog。每个类都实现方法来命名该实体。然而,由于它们各自的实现是独立的,每个类有不同的语法来获取名称。Planet类的代码如下:

同样,Car类的代码如下:

Dog类的代码如下:

显而易见任何使用这些类的人都需要翻看文档来查明如何获取每个对象的名字(这太糟糕了)。尽管查看文档不算是世界上最糟糕的命运,但如果一个项目(或公司)中的所有类使用相同的命名约定会让生活变得更加容易。这就是为什么会有Nameable接口。

所以可以为所有需要使用名字的类制定一个契约。用户在使用各种各样的类时无须查明命名对象的当前语法。Planet类、Car类和Dog类拥有相同的命名语法。

为了实现该崇高的目标,我们可以创建一个接口(我们可以使用之前用过的Nameable接口)。约定是所有类必须实现Nameable接口。因此如果所有类都遵循该命名约定,那么用户只需记住一个接口即可: ...

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