实例化接口 [英] Instantiate an Interface

查看:156
本文介绍了实例化接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扩展初始化接口?中提出的问题,我们确实实例化了一个接口,同时初始化它实现了类。

Extending the question asked in Initializing an Interface? , we do instantiate an Interface while initialize it with implemented class.

我的问题是为什么首先我们用接口实例化它?为什么我不能用实现的类直接实例化它?
例如。 :

My question is why in the first place, we are instantiate it with the Interface? Why can't I directly instantiate it with implemented class? For eg. :

Doc mydoc = new SimpleDoc();

Doc是接口,SimpleDoc正在实现它。

有什么问题SimpleDoc mydoc = new SimpleDoc();
这会失败吗?

Where Doc is interface and SimpleDoc is implementing it. What is the problem with SimpleDoc mydoc = new SimpleDoc(); Where this will fail?

推荐答案

依赖于抽象类型(接口或抽象类)通常是一种好习惯一个系统。

It's generally good practice to depend on abstract types (interfaces or abstract classes) within a system.

在你的例子中,你确实可以写:

In your example, you could indeed write:

SimpleDoc mydoc = new SimpleDoc()

但问题是使用 mydoc 将取决于具体类型 SimpleDoc 。这不一定是一个问题,但是,假设你创建一个 Doc 的新实现,比如说 ComplexDoc

However the problem is that code that uses mydoc will depend on the concrete type SimpleDoc. This isn't necessarily a problem in itself, however, suppose you create a new implementation of Doc, say ComplexDoc.

您将声明更改为:

ComplexDoc mydoc = new ComplexDoc();

现在你传递的所有场所方法 mydoc 也将不得不改变。

Now all the places methods that you pass mydoc to would also have to change.

但是你首先使用 Doc ,你只需要进行一次更改:

However had you used Doc in the first place you'd have a single change to make with:

Doc mydoc = ComplexDoc();

当您使用Collections API时,这一点特别有用,其中通常切换一个实现另一个或在测试用例中使用Mocking时。

This is particularly useful when you are working with the Collections API, where it's common to switch one implementation of another or when using Mocking in test case.

这篇关于实例化接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆