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

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

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

5.6 设计时请考虑可扩展性

给一个类添加新特性应该与扩展一个已有的类、添加一些新方法、修改其他行为一样简单。没必要重写所有事情。这正是继承扮演的功能。如果编写了一个Person类,必须考虑事实上稍后你可能会写Employee类和Customer类。因此,让Employee类继承Person可能是最好的策略。这种情况下Person类被称为可扩展的类。设计Person类时不应该包含一些阻止它可以被诸如Employee或Customer类继承的行为(假设在你的设计中,确实想让其他类扩展Person)。例如,你不应该在Employee类中加入具体的监管功能。如果你这样做了,那么其他不需要监管功能的类继承自Employee,就会出现问题。

这点触及了之前讨论过的抽象准则。Person应该只包含具体某人的数据和行为。其他类可以成为它的子类从而继承相应的数据和行为。

正如我们将在第11章和第12章的SOLID中所讨论的,类应该为扩展而打开,但为修改而关闭。通过首先使用接口并对其进行编码,你可以使用各种模式(例如Decorator)来扩展内容,而不必接触经过测试和部署的代码。

什么样的属性和方法应该是静态的?

静态方法增加了类的耦合性。你不能抽象出一个静态方法。你也不能模拟一个静态方法或者静态类。你不能提供一个静态接口。只有一种情况,在应用程序开发中(框架开发有所不同)使用静态类是合理的:你在开发帮助类或者不会产生任何副作用的扩展方法。例如,一个进行加法的静态方法。处理数据库交互或者Web服务不适合使用静态类。

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