Real life example is provided in System.Data.Common namespace that has abstract base classes which include DbConnection, DbCommand, and DbDataAdapter and are shared by the .NET Framework data providers, such as System.Data.SqlClient and System.Data.OracleClient which enable a developer to write generic data access code that does not depend on a specific data provider.
DbProviderFactories class provides static methods for creating a DbProviderFactory instance. The instance then returns a correct strongly typed object based on provider information and the connection string supplied at run time.
Example:
DataTable allProvidersTable = DbProviderFactories.GetFactoryClasses();
/* Getting SqlClient family members */
DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");
DbCommand dbCommand = dbProviderFactory.CreateCommand();
DbConnection dbConnection = dbProviderFactory.CreateConnection();
DbDataAdapter dbDataAdapter = dbProviderFactory.CreateDataAdapter();
SqlClientFactory sqlClientFactory = (SqlClientFactory)dbProviderFactory;
SqlConnection sqlConnection = (SqlConnection)dbConnection;
SqlCommand sqlCommand = (SqlCommand) dbCommand;
SqlDataAdapter sqlDataAdapter = (SqlDataAdapter) dbDataAdapter;
/* Getting OracleClient family members*/
dbProviderFactory = DbProviderFactories.GetFactory("System.Data.OracleClient");
dbCommand = dbProviderFactory.CreateCommand();
dbConnection = dbProviderFactory.CreateConnection();
dbDataAdapter = dbProviderFactory.CreateDataAdapter();
OracleClientFactory oracleClientFactory = (OracleClientFactory)dbProviderFactory;
OracleConnection oracleConnection = (OracleConnection)dbConnection;
OracleCommand oracleCommand = (OracleCommand)dbCommand;
OracleDataAdapter oracleDataAdapter = (OracleDataAdapter)dbDataAdapter;
Example-2
Code Solution architecture
Concrete factory instances are provided using static Factory method as below
public class FurnitureProviderFactory
{
public static IFurnitureFactory GetFactory(string furnitureType)
{
if (furnitureType == "Wood")
{
return new WoodenFurnitureFactory();
}
if (furnitureType == "Plastic")
{
return new PlasticFurnitureFactory();
}
throw new Exception("Undefined Furniture");
}
}