Contoh kehidupan nyata disediakan di namespace System.Data.Common yang memiliki kelas dasar abstrak yang mencakup DbConnection, DbCommand, dan DbDataAdapter dan dibagikan oleh penyedia data .NET Framework, seperti System.Data.SqlClient dan System.Data.OracleClient yang mana memungkinkan pengembang untuk menulis kode akses data generik yang tidak bergantung pada penyedia data tertentu.
Kelas DbProviderFactories menyediakan metode statis untuk membuat instance DbProviderFactory. Instance kemudian mengembalikan objek yang diketik dengan kuat berdasarkan informasi penyedia dan string koneksi yang diberikan pada waktu proses.
Contoh:
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;
Contoh-2
Arsitektur Solusi Kode
Instans pabrik beton disediakan menggunakan metode Pabrik statis seperti di bawah ini
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");
}
}