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

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

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

12.1.5 DIP:依赖倒置原则

依赖倒置原则(DIP)指出,代码应依赖抽象。通常,术语依赖倒置和依赖注入似乎可以互换使用。但是,在讨论此原则时,需要理解以下一些关键术语:

·依赖倒置——倒置依赖关系的原则

·依赖注入——倒置依赖关系的行为

·构造函数注入——通过构造函数执行依赖注入

·参数注入——通过方法的参数执行依赖注入,就像setter

依赖倒置的目标是将抽象的东西而不是具体的东西组合起来。

尽管显然在某些时候必须创建一些具体的对象,我们努力最晚创建尽可能具体的对象(通过使用new关键字),例如在main()方法中。对此有一种更好的思考方式,可重新阅读第8章的内容,在该章中我们讨论了在运行时加载类,以及第9章,我们在其中讨论了解耦和创建职责有限的小类。

同样,依赖倒置原则的目标之一是在运行时而不是在编译时选择对象(你可以在运行时更改程序的行为)。你甚至可以编写新类而不必重新编译旧类(实际上,你可以编写新类并将其注入)。

第11章中的内容为此讨论打下了基础。我们基于第11章来考虑依赖倒置原则。

步骤1:初始示例

对于本示例的第一步,我们再次回顾本书中使用的经典的面向对象设计示例之一,即Mammal类以及继承自哺乳动物的Dog和Cat类。Mammal类是抽象的,并且包含一个名为makeNoise()的方法。

诸如Cat等子类使用继承来获取Mammal类的行为,即makeNoise():

主应用程序实例化了一个Cat对象并调用了makeNoise方法:

初始示例完整的应用程序代码如下所示: ...

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