为什么类往往是时下定义界面? [英] Why classes tend to be defined as interface nowadays?

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

问题描述

这2-3过去几年中,很多项目我看,就像凯霍加开源C#CMS,倾向于定义持久性和非持久性类为接口。为什么?是否有一个很好的理由? 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.

一个简单的例子:

假设你有一个计算emplyoee工资的方法。作为其签名的一部分,它接受一个对象,计算他们的利益,说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.

现在,如果你使用的签名

Now if you use the signature

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.

这其实是松散的只是一个特例耦合:需求尽量少从代码的其他部分。在这种情况下,不要求一定的类;而不是仅仅要求某些方法存在,这是一个接口也正是

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天全站免登陆