首页 > 代码库 > Abstract Factory(抽象工厂模式)

Abstract Factory(抽象工厂模式)

System.Data.Common.DbProviderFactory
public abstract class DbProviderFactory
{
   public virtual DbConnection CreateConnection()
  {
     return null;
  }
   public virtual DbCommand CreateCommand()
  {
     return null;
  }
}
 
System.Data.SqlClient.SqlClientFactory
public sealed class SqlClientFactory : DbProviderFactory, IServiceProvider
{
   public override DbConnection CreateConnection()
  {
     return new SqlConnection();
  }
  public override DbCommand CreateCommand()
  {
    return new SqlCommand();
  }
}
 
System.Data.Odbc.OdbcFactory
public sealed class OdbcFactory : DbProviderFactory
{
  public override DbConnection CreateConnection()
  {
    return new OdbcConnection();
  }
  public override DbCommand CreateCommand()
  {
    return new OdbcCommand();
  }
}
 
System.Data.Common.DbConnection
public abstract class DbConnection : Component, IDbConnection
{
}
 
System.Data.SqlClient.SqlConnection
public sealed partial class SqlConnection : DbConnection, ICloneable
{
}
 
System.Data.Odbc.OdbcConnection
public sealed partial class OdbcConnection : DbConnection, ICloneable
{
}
 
System.Data.Common.DbCommand
public abstract class DbCommand : Component, IDbCommand
{
}
 
System.Data.SqlClient.SqlCommand
public sealed class SqlCommand : DbCommand, ICloneable
{
}
 
System.Data.Odbc.OdbcCommand
public sealed class OdbcCommand : DbCommand, ICloneable
{
}

 

public class Client
{
public static void Main()
{
    string connectionString =
System.Configuration.ConfigurationManager.AppSettings["DB_CONNECTION_STRING"];
    string providerName =
System.Configuration.ConfigurationManager.AppSettings["DB_PROVIDER_NAME"];
    DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
    DbConnection connection = factory.CreateConnection();
    connection.ConnectionString = connectionString;
    using (connection)
    {
      DbCommand command = factory.CreateCommand();
      command.CommandText =
"INSERT INTO t_users(user_username, user_password) VALUES(‘admin‘ ,‘admin))";
      command.Connection = connection;
      command.ExecuteNonQuery();
    }
  }
}