Rya*_*yan 15 c# architecture design-patterns
可能重复:
接口与基类
通常可以看到使用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) {}
}
Run Code Online (Sandbox Code Playgroud)
但你可以使用抽象类同样地做到这一点.
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); {}
}
Run Code Online (Sandbox Code Playgroud)
在存储库方案中使用Interface over Abstract Class有哪些具体优势?
(即不要只是告诉我你可以实现多个接口,我已经知道了 - 为什么你会在存储库实现中这样做)
编辑澄清 - 像" MSDN - 在类和接口之间选择"之类的页面可以被解释为"除非有充分的理由不在接口上选择类" - 在存储库模式的特定情况下有什么好的理由
在这种情况下,使用接口而不是抽象类的主要优点是接口是完全透明的:这更多的是一个问题,您无权访问所继承的类的源。
然而,这种透明度允许您生成已知范围的单元测试:如果您测试一个接受接口作为参数的类(使用依赖项注入方法),您就知道您正在使用已知数量测试该类;接口的测试实现将仅包含您的测试代码。
同样,在测试存储库时,您知道您只是在测试存储库中的代码。这有助于限制测试中可能的变量/交互的数量。
| 归档时间: |
|
| 查看次数: |
8834 次 |
| 最近记录: |