我的问题很简单:如果它们是由单个类实现的,那么使用接口是否有任何优势? 我一直认为只有当该接口有多个实现时,接口才是好的。
My question is simple: is there any advantage of using interfaces if they are implemented by a single class ? I always thought that interfaces are good only when there are multiple implementations of that interface.
谢谢。
推荐答案总之:没有。接口所指的合同可以直接在您的唯一类中指定。
In a word: no. The contract that an interface means can be specified directly in your only class.
如果您明确表示将来不需要再使用相同的方法,你可以避免定义一个接口。
If you are clear that you won't need another implementation of the same methods in the future, you can avoid defining an interface.
当然,这里的问题是未来条款。如果项目很小,没有很长的开发/升级期,并且定义明确,那么您几乎可以确定将来需要什么。
Of course, the issue here is "in the future" clause. If the project is small, without a long development/upgrade period, and well defined, you can be almost sure about what will be needed in the future.
如果项目很长一段时间它可能会发生变化,那么你将不得不考虑:
If the project is long as is probably that it will be subjected to changes, then you will have to factor in:
- 你最终需要一个接口的概率。
- 你现在知道接口将来需要什么方法的概率。
- 现在做界面的成本与将来的重构有关。
更多推荐
Java中的接口优势
发布评论