Search code examples
c#design-patternsdata-access-layerabstract-factory

Correct approach on implementing abstract factory pattern?


I am about to build a data access layer the good old ado.net way. Traditionally I would have built the dal according to a simple repository pattern. But this time I wanna give the Abstract Factory pattern a try because I have read about this pattern in an article lately.

So here I am try to code a dal with the abstract factory pattern. First of let me explain what I got so far. What I wanna know afterwards is whether my approach is the correct way of implementing this pattern and what the advantages are towards the repository approach.

So I wrote the following classes:

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

So my questions in short: 1) Is this a correct implementation of the abstract factory pattern? 2) What can be done better? 3) What is the advantage towards different repository classes which inherit from a base class?

Thx a lot guys.

If you need more information on my code please tell me. But there is no more at this point of time!


Solution

  • Abstract db provider factory already exist in .Net. Its called DbProviderFactory. You can create different concrete factories via

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

    Why not to use what is already in box?

    Here you can read more about DbProviderFactories and how to add custom factory implementations.