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

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

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

5.3 设计健壮的构造函数(以及析构函数)

当设计类时,最重要的设计问题之一是如何构造类。第3章中我们讨论了构造函数。如果需要温习设计构造函数的准则,可以回顾一下第3章。

首先并且最重要的一点是,构造函数应该把对象设置为安全的初始状态。这包括了属性初始化以及内存管理等问题。你也需要确保在默认的条件下能正确地构造对象。通常提供一个构造函数来处理默认情况是个好主意。

在包含析构函数的语言中,析构函数包括了正确的清除功能,这也很重要。在大多数情况下,清除功能就是释放对象在某些时间点被分配的系统内存。Java和.NET通过垃圾集合机制自动地回收内存。在诸如C++的语言中,开发人员必须在析构函数使用代码来正确地释放对象生存期被分配的内存。如果忽略了该功能,结果会导致内存泄漏。

构造函数注入

这是一个介绍构造函数注入很好的点:在对象(通过构造函数)被创建的时候,服务类被注入,而不是在类内部被关键字new创建。例如,出租车司机能通过构造函数,得到他的出租车号码牌对象,他的无线电信息对象(频率、呼叫信号等),以及发动出租车的钥匙。

内存泄漏

当对象在其生命周期中没有正确释放被分配的内存时,一旦创建了该对象的应用程序还在执行,那么这块内存对整个系统来说是不可用的。例如,假设在一些循环中,创建了同一个类的多个对象,并且销毁了这些对象。如果这些对象在生命周期末期没有正确地释放占用的内存,内存泄漏会慢慢地减少系统可用内存池。某一时刻,所有的内存都被使用了,而系统则没有可用的内存供分配。这意味着在该系统中执行的其他应用程序则不能分配到任何内存。这将导致应用程序进入不稳定的状态,甚至会锁定系统。

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