接口的好案例 [英] Good Case For Interfaces

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

问题描述

我在一家公司工作,有些人需要证明在我们的代码中使用接口的理由(Visual Studio C# 3.5).

I work at a company where some require justification for the use of an Interface in our code (Visual Studio C# 3.5).

我想问一下需要接口的 Iron Clad 推理.(我的目标是证明接口是编程的正常部分.)

I would like to ask for an Iron Clad reasoning that interfaces are required for. (My goal is to PROVE that interfaces are a normal part of programming.)

我不需要说服,我只需要一个很好的论据来说服别人.

I don't need convincing, I just need a good argument to use in the convincing of others.

我正在寻找的论点是基于事实的,而不是基于比较的(即因为 .NET 库使用它们"是基于比较的.)

The kind of argument I am looking for is fact based, not comparison based (ie "because the .NET library uses them" is comparison based.)

反对它们的论点是:如果一个类被正确设置(带有它的公共和私有成员),那么接口只是额外的开销,因为那些使用该类的人仅限于公共成员.如果您需要一个由 1 个以上类实现的接口,那么只需设置继承/多态即可.

The argument against them is thus: If a class is properly setup (with its public and private members) then an interface is just extra overhead because those that use the class are restricted to public members. If you need to have an interface that is implemented by more than 1 class then just setup inheritance/polymorphism.

推荐答案

代码解耦.通过对接口进行编程,您可以将使用接口的代码与实现接口的代码分离.这允许您更改实现而无需重构所有使用它的代码.这与继承/多态性结合使用,允许您交替使用多种可能的实现中的任何一种.

Code decoupling. By programming to interfaces you decouple the code using the interface from the code implementing the interface. This allows you to change the implementation without having to refactor all of the code using it. This works in conjunction with inheritance/polymorphism, allowing you to use any of a number of possible implementations interchangeably.

模拟和单元测试.当方法是虚拟的时,模拟框架最容易使用,默认情况下,您通过接口获得.这实际上是我创建界面的最大原因.

Mocking and unit testing. Mocking frameworks are most easily used when the methods are virtual, which you get by default with interfaces. This is actually the biggest reason why I create interfaces.

定义可能适用于许多不同类的行为,允许它们互换使用,即使类之间没有关系(除了定义的行为).例如,一个 Horse 和一个 Bicycle 类可能都有一个 Ride 方法.您可以定义一个接口 IRideable 来定义 Ride 行为,任何使用此行为的类都可以使用 Horse 或 Bicycle 对象,而不会在它们之间强制进行非自然的继承.

Defining behavior that may apply to many different classes that allows them to be used interchangeably, even when there isn't a relationship (other than the defined behavior) between the classes. For example, a Horse and a Bicycle class may both have a Ride method. You can define an interface IRideable that defines the Ride behavior and any class that uses this behavior can use either a Horse or Bicycle object without forcing an unnatural inheritance between them.

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

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