Abstract Factory Design Pattern - DbProviderFactory - Factory Method
by David Hayden ( ASP.NET Developer )
This didn't hit me until the other day, but DbProviderFactory is a great example of the Abstract Factory Design Pattern.
I checked my source for design patterns, Designs Patterns in C# by Steven John Metsker, and he defines Abstract Factory as such:
“There will be times when you want to provide for object creation while retaining control of which class to instantiate. In such circumstances, you can apply the Factory Method pattern with a method that uses an outside factor to determine which class to instantiate. Sometimes the factor that controls which object to instantiate can be thematic, running across several classes. The Abstract Factory pattern addresses this situation. Its intent is to provide for the creation of families of related or dependent objects.”
This is exactly the case with DbProviderFactory. There are several concrete versions of this abstract class:
- System.Data.Odbc.OdbcFactory
- System.Data.OleDb.OleDbFactory
- System.Data.OracleClient.OracleClientFactory
- System.Data.SqlClient.SqlClientFactory
and each class is responsible for creating a family of classes ( as you can see from its public methods ):
- CreateCommand - Returns a new instance of the provider's class that implements the DbCommand class.
- CreateCommandBuilder - Returns a new instance of the provider's class that implements the DbCommandBuilder class.
- CreateConnection - Returns a new instance of the provider's class that implements the DbConnection class.
- CreateConnectionStringBuilder - Returns a new instance of the provider's class that implements the DbConnectionStringBuilder class.
- CreateDataAdapter - Returns a new instance of the provider's class that implements the DbDataAdapter class.
- CreateDataSourceEnumerator - Returns a new instance of the provider's class that implements the DbDataSourceEnumerator class.
- CreateParameter - Returns a new instance of the provider's class that implements the DbParameter class.
- CreatePermission - Returns a new instance of the provider's class that implements the provider's version of the CodeAccessPermission class.
Each public method is a Factory Method, because it creates an object but you don't know what class will be instantiated. Each method returns only an abstract class, DbCommand in the case of CreateCommand for example.
I love it when things click like that and you start to see frameworks in terms of their design patterns.
Source: David Hayden ( ASP.NET Developer )
Design Patterns Resources and Tutorials