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

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

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

8.3.2 接口

在定义接口之前,请注意C++没有叫作接口的结构体。当使用C++时,你可以使用抽象类的语法子集创建一个接口。例如,以下的C++代码是一个抽象类。然而由于该类中的唯一一个方法是一个虚方法,所以没有任何实现。结果该抽象类提供了与接口相同的功能。

接口术语

这又一次造成了软件术语的混淆,而且非常混淆。请注意你可以在不同场景下使用术语接口,所以请确保在正确的上下文中使用它。

第一,当涉及用户交互的可视化接口(比如和显示器)时,会广泛使用图形化用户接口(GUI)。

第二,类的接口基本上是指其方法签名。

第三,在Objective-C和Swift语言中,接口和实现会将代码在物理上分割为不同的模块。

第四,接口和协议本质上是父类和子类之间的契约。

你还能想出其他关于接口的概念吗?

这有个明显的问题,如果抽象类能够提供与接口一样的功能,那么为什么Java和.NET还要提供名为接口的结构呢?而且为什么Objective-C和Swift提供协议?

一方面,C++支持多重继承,而Java、Objective-C和.NET却不支持。尽管Java、Objective-C和.NET类只能继承自一个父类,但它们可以实现多个接口。使用多个抽象类构成了多重继承。所以Java和.NET并不支持多重继承。总之,当使用接口时,你无须考虑正式的继承体系,如果设计上是合理的,理论上你可以为任何类添加接口。而抽象类要求你继承自该抽象类,并且延伸至其自身所有可能的父类。

圆

基于这些考虑,接口往往作为缺少多重继承情况下的一种替代方案。不过从技术角度来说并不是这样。接口是独立的设计技术,虽然使用多重继承也可以完成对应用程序的设计,但接口并不是替代或回避使用多重继承。 ...

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