我什么时候想在实际的类上声明接口? [英] When do I want to declare interface over the actual class?
问题描述
例如,我经常看到:
Set<Integer> s = new TreeSet<Integer>();
Set<Integer> s = new HashSet<Integer>();
Map<Integer, String> m = new HashMap<Integer, String>();
over
TreeSet<Integer> ts = new TreeSet<Integer>();
HashSet<Integer> hs = new HashSet<Integer>();
HashMap<Integer, String> hm = new HashMap<Integer, String>();
前者与后者有什么优势/劣势?
What are the advantages/disadvanges of the former vs the latter?
推荐答案
对我而言,它归结为许多要点。
For me it comes down to a number of points.
您是否关心实施?您的代码是否需要知道 Map
是 HashMap
或 TreeMap
?或者它只关心它有某种键/值结构
Do you care about the implementation? Does your code need to know that the Map
is a HashMap
or a TreeMap
? Or does it just care that it's got a key/value structure of some kind
这也意味着当我构建我的实现代码时,如果我公开一个方法,返回Map,我可以随着时间的推移改变实现,而不会影响任何依赖它的代码(因此尝试构建这些类型的值是个坏主意的原因)
It also means that when I'm building my implementation code, if I expose a method that returns Map, I can change the implementation over time without effecting any code that relies on it (hence the reason why it's a bad idea to try and cast these types of values)
另一个是在代码周围移动这些结构变得更容易,这样任何可以接受 Map
的方法都会更容易处理,然后依赖于在 HashMap上
例如
The other is that it becomes easier to move these structures around the code, such that any method that can accept a Map
is going to be easier to deal with then one that relies on a HashMap
for instance
约定(我遵循)基本上是使用最低功能接口需要API。没有必要使用不提供API所需功能的接口(例如,如果您需要 SortedMap
,使用 Map
然后)
The convention (that I follow) is basically to use the lowest functional interface that meets the need of the API. No point using an interface that does not provide the functionality your API needs (for example, if you need a SortedMap
, no point using a Map
then)
恕我直言
这篇关于我什么时候想在实际的类上声明接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!