Abstract Factory Pattern


In this article I would like to explain the Abstract Factory pattern. This pattern is essential for learning the Factory Method and Bridge patterns.

Challenge

You are working on an ORM (Object Relational Mapping) framework creation. The framework could be used in different databases like:

  • Sql Server
  • Oracle
  • MS Access
  • OleDb

Based on the database type, you need to create related classes like:\

  • SqlConnection, SqlCommand when Sql server
  • OracleConnection, OracleCommand when Oracle etc.

How to create a family of related objects without implementation of them?

Definition

"Provide an interface for creating families of related or dependent objects without specifying their concrete classes."

Implementation

Our idea is to create an interface which contains all related objects like:

public abstract class DbProviderFactory
{
    public abstract DbConnection CreateConnection();
    public abstract DbCommand CreateCommand();
}


Luckily, ADO.NET already includes the same interface as Abstract Factory. The The definition is given below: (I have excluded some irrelevant methods from it)

namespace System.Data.Common
{
    public abstract class DbProviderFactory
    {
        public virtual DbCommand CreateCommand();
        public virtual DbCommandBuilder CreateCommandBuilder();
        public virtual DbConnection CreateConnection();
        public virtual DbDataAdapter CreateDataAdapter();
        public virtual DbParameter CreateParameter();
    }
}

From the above code we can see that the related classes are includes as a family without going to the implementation details.

The abstract class DbProviderFactory contains related classes which are abstract: DbCommand, DbConnection etc.

Concrete Implementations

ADO.NET provides the following implementations of the above abstract class DbProviderFactory.

  • System.Data.SqlClient.SqlClientFactory
  • System.Data.OleDb.OleDbFactory

The above classes implements all abstract methods from the base class. Thus it will be providing concrete implementations of DbConnection which is SqlConnection, DbCommand which is SqlCommand etc.

Instantiating from the above classes, we can start using the concrete implementations like following code.

SqlClientFactory factory = SqlClientFactory.Instance;

DbConnection connection = factory.CreateConnection();
DbCommand command = factory.CreateCommand();

command.Connection = connection;
command.CommandText = "query here";
command.ExecuteNonQuery();

FactoryPtrn.gif

Summary

In this article we have seen the usage of Abstract Factory pattern through inbuilt ADO.NET DbProviderFactory class. In the next article of Factory Method pattern the above discussed code will be used. So I am not attaching any source code with this article.
 

Up Next
    Ebook Download
    View all
    Learn
    View all