在存储库模式中使用接口而不是抽象类的优势? [英] Advantage of using Interface over abstract class for repository pattern?
问题描述
可能的重复:
接口与基类
常见的是使用接口实现的存储库模式
Its common to see the repository pattern implemented using Interfaces
public interface IFooRepository
{
Foo GetFoo(int ID);
}
public class SQLFooRepository : IFooRepository
{
// Call DB and get a foo
public Foo GetFoo(int ID) {}
}
public class TestFooRepository : IFooRepository
{
// Get foo from in-memory store for testing
public Foo GetFoo(int ID) {}
}
但是你同样可以使用抽象类来做到这一点.
But you could equally do this using abstract classes.
public abstract class FooRepositoryBase
{
public abstract Foo GetFoo(int ID);
}
public class SQLFooRepository : FooRepositoryBase
{
// Call DB and get a foo
public override Foo GetFoo(int ID); {}
}
public class TestFooRepository : FooRepositoryBase
{
// Get foo from in-memory store for testing
public override Foo GetFoo(int ID); {}
}
在存储库场景中使用接口而不是抽象类有哪些具体优势?
(即不要只是告诉我你可以实现多个接口,我已经知道了——你为什么要在存储库实现中这样做)
编辑以澄清 - 页面如MSDN- 在类和接口之间选择"可以解释为选择类而不是接口,除非有充分的理由不这样做"-在存储库模式的特定情况中的充分理由是什么?
Edit to clarify - pages like "MSDN - Choosing Between Classes and Interfaces" can be paraphrased as "Choose classes over interfaces unless there is a good reason not to" - what are the good reasons in the specific case of a Repository pattern
推荐答案
在这个实例中使用接口而不是抽象类的主要优点是接口是完全透明的:这更像是一个你不知道的问题可以访问您继承的类的源代码.
The main advantage of using an interface over an abstract class in this instance is that an interface is entirely transparent: This is more of an issue where you don't have access to the source of the class you're inheriting from.
但是,这种透明性允许您生成已知范围的单元测试:如果您测试一个接受接口作为参数的类(使用依赖注入方法),您就知道您正在测试具有已知数量的类;接口的测试实现将只包含您的测试代码.
However, this transparency allows you to produce unit tests of a known scope: If you test a class that accepts an interface as a parameter (using the dependency injection method), you know you're testing the class with a known quantity; the testing implementation of the interface will only contain your testing code.
同样,在测试存储库时,您知道您只是在测试存储库中的代码.这有助于限制测试中可能的变量/交互的数量.
Similarly, when testing your repository, you know you're testing just your code in the repository. This helps to limit the number of possible variables/interactions in the test.
这篇关于在存储库模式中使用接口而不是抽象类的优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!