为什么我要使用接口? [英] Why would I want to use Interfaces?

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

问题描述

我知道他们强迫您实现方法等,但我无法理解的是您为什么要使用它们.谁能给我一个很好的例子或解释我为什么要实现这个.

I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.

推荐答案

一个具体的例子:接口是指定其他人的代码必须满足的契约的好方法.

One specific example: interfaces are a good way of specifying a contract that other people's code must meet.

如果我正在编写代码库,我可能会编写对具有特定行为集的对象有效的代码.最好的解决方案是在接口中指定这些行为(没有实现,只有描述),然后在我的库代码中使用对实现该接口的对象的引用.

If I'm writing a library of code, I may write code that is valid for objects that have a certain set of behaviours. The best solution is to specify those behaviours in an interface (no implementation, just a description) and then use references to objects implementing that interface in my library code.

然后任何随机的人都可以出现,创建一个实现该接口的类,实例化该类的一个对象并将其传递给我的库代码并期望它工作.注意:当然可以严格实现一个接口而忽略接口的意图,所以仅仅实现一个接口并不能保证一切都会好起来.傻子总有办法!:-)

Then any random person can come along, create a class that implements that interface, instantiate an object of that class and pass it to my library code and expect it to work. Note: it is of course possible to strictly implement an interface while ignoring the intention of the interface, so merely implementing an interface is no guarantee that things will work. Stupid always finds a way! :-)

另一个具体示例: 两个团队致力于必须合作的不同组件.如果两个团队在第一天坐下来就一组接口达成一致,那么他们就可以分道扬镳,围绕这些接口实现他们的组件.团队 A 可以构建测试工具来模拟团队 B 的组件进行测试,反之亦然.并行开发,错误更少.

Another specific example: two teams working on different components that must co-operate. If the two teams sit down on day 1 and agree on a set of interfaces, then they can go their separate ways and implement their components around those interfaces. Team A can build test harnesses that simulate the component from Team B for testing, and vice versa. Parallel development, and fewer bugs.

关键是接口提供了一层抽象,这样你就可以编写无视不必要细节的代码.

The key point is that interfaces provide a layer of abstraction so that you can write code that is ignorant of unnecessary details.

大多数教科书中使用的规范示例是排序例程的示例.只要您有办法比较任意两个对象,就可以对任何类别的对象进行排序.因此,您可以通过实现 IComparable 接口使任何类可排序,该接口强制您实现用于比较两个实例的方法.所有的排序例程都是为了处理对 IComparable 对象的引用而编写的,所以只要你实现了 IComparable,你就可以在你的类的对象集合上使用这些排序例程中的任何一个.

The canonical example used in most textbooks is that of sorting routines. You can sort any class of objects so long as you have a way of comparing any two of the objects. You can make any class sortable therefore by implementing the IComparable interface, which forces you to implement a method for comparing two instances. All of the sort routines are written to handle references to IComparable objects, so as soon as you implement IComparable you can use any of those sort routines on collections of objects of your class.

这篇关于为什么我要使用接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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