接口编码? [英] Coding to interfaces?
问题描述
我想巩固我对编码到界面"概念的理解.据我了解,人们创建接口来描述预期的功能,然后在具体的类中实现这些契约".要使用接口,可以简单地调用具体类实例上的方法.
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.
基于以上:
- 我对接口编码"的理解有误区吗?
- 我错过了对接口进行编码的任何好处吗?
谢谢.
推荐答案
只有一个可能的更正:
要使用接口,可以简单地调用具体类的实例上的方法.
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.
你会发现像 spring 这样的框架和 guice 鼓励对接口进行编程.它是诸如 aspect-oriented的基础a> 编程、自动生成的事务管理代理等
You'll find that frameworks like spring and guice encourage programming to an interface. It's the basis for ideas like aspect-oriented programming, auto generated proxies for transaction management, etc.
这篇关于接口编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!