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

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

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

第11章 避免依赖和高度耦合的类

如第1章提到的,传统的面向对象编程的原则是封装、继承、多态性。理论上,任何一种面向对象的编程语言都必须遵从上述三个原则。此外,同第1章的观点一样,原则中需要加上组合。

因此,当我教授面向对象编程时,面向对象的基本概念如下:

·封装

·继承

·多态性

·组合

提示

读者可能觉得应该把接口加入原则列表,但是我认为接口只是继承的一种特殊形式。

在当前的开发环境下,如何合适地使用继承已成为开发者讨论的焦点,所以将组合这个概念加入列表是非常必要的。关于使用继承的担忧并不是最近才出现的。在过去几年中,相关的讨论已经越来越白热化。许多开发者倡议使用组合代替继承(经常称为组合优于继承)。实际上,很多开发者完全避免使用继承,或者限制继承的层级为单层。

关注如何使用继承的原因在于解决耦合的相关问题。使用继承的争议点主要在于复用性、可扩展性和多态性。继承会创建类之间的依赖关系,造成了类之间的耦合。这些依赖关系会给代码维护和测试带来潜在的问题。

在第7章,我们讨论了继承在某些情况下可能会弱化封装,这看起来违反直觉,因为两者都是基础的概念。尽管如此,这正是有意思的地方,要求我们真正地思考如何使用继承。

小心

明确一下我并不是提倡要避免使用继承。本章讨论的是避免依赖和高度耦合的类。在何时使用继承是讨论的很重要的一部分。

这些争论也引出了下面的问题:如果不用继承,那么应该用什么?最简单的答案就是组合。这一点也不令人惊讶,因为我在整本书里都说明了重用类的实现方式只有两种:继承和组合。你可以通过继承从父类创建一个子类,或者使用组合的方式在一个类里包含另一个类。

如果像某些人提倡的那样要完全避免使用继承,那么我们为什么要花时间去学习?答案很简单:因为很多代码都用到了继承。大部分的开发者很快就会了解,他们碰到的绝大部分的代码都是需要维护的代码。因此,理解如何修复、增强和维护使用继承的老旧代码非常重要。而且你也可能会使用继承写新代码。简而言之,开发者需要掌握所有的基础知识和技能。然而,这也意味着我们在添加新技能的时候要仔细斟酌该如何使用它们。 ...

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