In this article I would like to explain the Abstract Factory pattern. This
pattern is essential for learning the Factory Method and Bridge patterns.
You are working on an ORM (Object Relational Mapping) framework creation. The
framework could be used in different databases like:
- Sql Server
- MS Access
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?
"Provide an interface for creating families of related or dependent objects
without specifying their concrete classes."
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)
public abstract class
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.
ADO.NET provides the following implementations of the above abstract class
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.
factory = SqlClientFactory.Instance;
connection = factory.CreateConnection();
command = factory.CreateCommand();
command.CommandText = "query here";
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.