在存储库模式中使用接口优于抽象类的接口? [英] Advantage of using Interface over abstract class for repository pattern?

查看:55
本文介绍了在存储库模式中使用接口优于抽象类的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
接口与基类

Possible Duplicate:
Interface vs Base class

常见的情况是使用接口实现存储库模式

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); {}
}

在存储库方案中,使用接口优于抽象类的具体优势是什么?

(即,不只是告诉我您可以实现多个接口,我已经知道了-为什么要在存储库实现中做到这一点)

编辑以澄清-类似""可以解释为除非有充分的理由,否则在接口上选择类"-在存储库模式的特定情况下的充分理由是什么?

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屋!

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