2

我即将以古老的 ado.net 方式构建数据访问层。传统上,我会根据简单的存储库模式构建 dal。但这次我想尝试一下抽象工厂模式,因为我最近在一篇文章中读到了这种模式。

所以在这里我尝试用抽象工厂模式编写一个dal。首先让我解释一下到目前为止我得到了什么。之后我想知道的是我的方法是否是实现这种模式的正确方法,以及存储库方法的优势是什么。

所以我写了以下类:

public abstract class Db
{
     //this is class will contain methods like:
     //public abstract IDbConnection CreateConnectionInstance();
}

public class SqlDb : Db
{
     //this is class will contain methods like:
     //public override IDbConnection CreateConnectionInstance()
     //{
     //      ... return new SqlConnection();
     //}
}

public class OracleDb : Db
{

}

public class MockupDb : Db
{

}

//this class generates the fitting provider but does not have a base (is this correct?)
public static class DbFactory
{
    public static Db CreateInstance(DbProviderType dbProviderType)
    {
        Db db = null;
        switch (dbProviderType)
        {
            case DbProviderType.Oracle:
                db = new OracleDb();
                break;
            case DbProviderType.Sql:
                db = new SqlDb();
                break;
            case DbProviderType.Mockup:
                db = new MockupDb();
                break;
            default:
                break;
        }
        return db;
    }
}

所以我的问题简而言之:1)这是抽象工厂模式的正确实现吗?2)什么可以做得更好?3)从基类继承的不同存储库类有什么优势?

谢谢很多人。

如果您需要有关我的代码的更多信息,请告诉我。但是现在没有更多了!

4

2 回答 2

3

.Net 中已经存在抽象数据库提供程序工厂。它称为DbProviderFactory。您可以通过创建不同的混凝土工厂

var factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
DbConnection connection = factory.CreateConnection();

为什么不使用盒子里已有的东西?

在这里,您可以阅读有关 DbProviderFactories 以及如何添加自定义工厂实现的更多信息。

于 2012-04-27T10:47:37.670 回答
0

I think, you mixed some concepts.

Repository allows you abstract away from the storage nature. It's a black box, which can give you an object, matching some criteria, and take it back. Repository internals can get or store object in multiple data sources (e. g. some object data stored in database, another part of data - in file, or in an external device, which cannot be described in terms of relational data source).

Factory can add more flexibility when working with ADO .NET data sources. But it is not a substitute of the repository. Repository can use factory to get particular data source implementation.

Upd. About your code sample - factory should throw exception, when provider's type is unknown.

于 2012-04-27T10:44:07.743 回答