为什么类现在倾向于定义为接口? [英] Why classes tend to be defined as interface nowadays?

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

问题描述

去年的这 2-3 年,我看到的许多项目,例如 Cuyahoga 开源 C# CMS,倾向于将持久性和非持久性类定义为 Interface.为什么?有充分的理由吗?TDD?嘲讽?设计模式?...

These 2-3 last years, many projects I see, like Cuyahoga open source C# CMS, tends to define persistent and non persistent classes as Interface. Why? Is there a good reason? TDD? Mocking? A design pattern? ...

推荐答案

主要原因是这使得像 依赖注入更容易.这反过来又使软件具有更大的灵活性,并且可以更轻松地重用和重组现有代码.这有用的例子包括各种形式的单元测试(如你所提到的),但也包括大多数其他形式的常规"测试.代码重用.

The main reason is that this makes techniques like dependency injection easier. This in turn allows for more flexibility in the software and easier reuse and recombination of existing code. Examples for where this is useful include the various forms of unit testing (as you mentioned), but also most other forms of "regular" code reuse.

一个简单的例子:

假设您有一种计算员工工资的方法.作为其签名的一部分,它接受一个计算其收益的对象,例如一个 BenefitCalculator 实例:

Say you have a method that calculates emplyoee salaries. As part of its signature, it accepts an object that calculates their benefits, say an instance of BenefitCalculator:

calculateSalary(... BenefitCalculator bc, ...)

最初,您的设计只有一个类 BenefitCalculator.但后来,事实证明你需要不止一个类,例如因为软件的不同部分应该使用不同的算法(可能是为了支持不同的国家,或者因为算法应该是用户可配置的......).在这种情况下,与其膨胀 BenefitCalculator 的现有实现,不如创建新类,例如BenefitCalculatorFrance 或 BenefitCalculatorSimple 等

Originally, your design has only one class BenefitCalculator. But later, it turns out that you need more than one class, e.g. because different parts of the software are supposed to use different algorithms (maybe to support different countries, or because the algorithm is supposed to be user-configurable...). In that case, rather than bloat the existing implementation of BenefitCalculator, it makes sense to create new class(es), e.g. BenefitCalculatorFrance, or BenefitCalculatorSimple etc.

现在如果你使用签名

calculateSalary(... BenefitCalculator bc, ...)

,你有点搞砸了,因为你不能提供不同的实现.但是如果你使用

, you are kind of screwed, because you cannot supply different implementations. If however you use

calculateSalary(... IBenefitCalculatorbc, ...)

calculateSalary(... IBenefitCalculator bc, ...)

你可以让所有的类都实现这个接口.

you can just have all classes implement the interface.

这实际上只是松耦合"的一个特例:对代码其他部分的需求尽可能少.在这种情况下,不要要求某个类;而只是要求存在某些方法,这正是接口所做的.

This is actually just a special case of "loose coupling": Demand as little as possible from other parts of the code. In this case, don't demand a certain class; instead just demand that certain methods exist, which is just what an Interface does.

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

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