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

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

问题描述

这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.

A简单的例子:

说你有一个计算工资的方法。作为其签名的一部分,它接受一个计算好处的对象,例如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(... IBenefitCalculator
bc,...)

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

你可以让所有的类实现界面。

you can just have all classes implement the interface.

这实际上只是一个特殊情况松散耦合:代码的其他部分的需求尽可能少。在这种情况下,不要求某一类;而只是要求存在某些方法,这就是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天全站免登陆