接口编码? [英] Coding to interfaces?

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

问题描述

我想巩固我对编码到界面"概念的理解.据我了解,人们创建接口来描述预期的功能,然后在具体的类中实现这些契约".要使用接口,可以简单地调用具体类实例上的方法.

I want to solidify my understanding of the "coding to interface" concept. As I understand it, one creates interfaces to delineate expected functionality, and then implements these "contracts" in concrete classes. To use the interface one can simply call the methods on an instance of the concrete class.

显而易见的好处是了解具体类提供的功能,而不管其具体实现如何.

The obvious benefit is knowing of the functionality provided by the concrete class, irrespective of its specific implementation.

基于以上:

  1. 我对接口编码"的理解有误区吗?
  2. 我错过了对接口进行编码的任何好处吗?

谢谢.

推荐答案

只有一个可能的更正:

要使用接口,可以简单地调用具体类的实例上的方法.

To use the interface one can simply call the methods on an instance of the concrete class.

人们会在类型接口的引用上调用方法,这恰好使用具体类作为实现:

One would call the methods on a reference of the type interface, which happens to use the concrete class as implementation:

List<String> l = new ArrayList<String>();
l.add("foo");
l.add("bar");

如果您决定切换到另一个 List 实现,则客户端代码无需更改即可运行:

If you decided to switch to another List implementation, the client code works without change:

List<String> l = new LinkedList<String>();

这对于隐藏实现细节、自动生成代理等特别有用.

This is especially useful for hiding implementation details, auto generating proxies, etc.

你会发现像 这样的框架和 鼓励对接口进行编程.它是诸如

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