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

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

问题描述

我知道他们强迫你实现方法等,但我不明白为什么你会想要使用它们。任何人都可以给我一个很好的例子或解释我为什么要实现它。

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! :-)

另一个具体的例子:两个团队正在处理必须合作的不同组件。如果两个团队在第1天坐下并同意一组接口,那么他们可以分别采用各种方式并围绕这些接口实现其组件。团队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.

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

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