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

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

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

4.5 访问器

在本书的绝大部分例子中,属性都被定义为私有的,所以其他对象无法直接访问属性。创建一个不会与其他对象交互的孤立对象是荒谬的,因为我们需要在对象间分享适当的信息。有时候是否有必要检查或修改另一个类中的属性?答案当然是需要。大多数时候一个对象需要访问其他对象的属性,不过不需要直接访问。

类应该很注意保护自身的属性。例如,我们不会让对象A在不受对象B控制的情况下检查或修改对象B中的属性。这样做有好几个理由。最重要的原因是要保证数据完整性以及高效调试。

假设Cab类存在一个缺陷。你已经追踪到问题出在Name属性上。不知什么原因它被覆盖了,查询名称会返回垃圾信息。如果Name是public的,任何类都可以修改它,你需要搜索所有可能的代码,尝试找到引用或修改了Name的地方。然而,如果你只允许Cabbie对象修改Name,你只需要查看Cabbie类。一种名为访问器的方法可以提供访问。有时访问器又被称为取值方法(getter)和赋值方法(setter),有时又被简单称为get()和set()。在本书中我们约定方法名加上set和get前缀,如下所示:

在该代码片段中,Supervisor对象会要求Cabbie对象返回其名称(如图4.4所示)。关键在于Supervisor对象自身无法直接获取该信息,它必须询问Cabbie对象来获得信息。这种理念可应用在很多地方。比如,你可能有一个setAge()方法可检查输入的年龄是0或者小于0。如果年龄小于0,setAge()方法可以拒绝设置这个不正确的值。通常,赋值方法可以在某种程度上确保数据的完整性。 ...

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