工厂模式-抽象工厂模式

定义

抽象工厂是工厂方法的升级版,为相关或者相互依赖的对象提供一个统一的接口,而且无需指定他们的具体实现类。

UML类图

优缺点

  • 优点
    • 对产品族进行约束,封装性好
  • 缺点
    • 产品族扩展困难,添加一个产品需要修改抽象和具体工厂类,违背开闭原则。

 代码:

 

1.Program.cs

public class Program
{
static void Main(string[] args)
{
DbFactory dbFactory = new SqlDbFactory();
SqlHelper sqlHelper = new SqlHelper(dbFactory);

int age = 18;
string selectSql = "select count(*) from [Users] where Age>@Age;";
object count = sqlHelper.ExecuteScalar(selectSql,
new DbParameter[] { sqlHelper.CreateDbParameter("@Age", age) });
Console.WriteLine($"共有{count}记录");
}
}

 

2.SqlHelper.cs

public class SqlHelper
{

DbFactory _dbFactory;

public SqlHelper(DbFactory dbFactory)
{
_dbFactory = dbFactory;
}

/// <summary>
/// 查询操作,返回查询结果中的第一行第一列的值
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public object ExecuteScalar(string sql, params DbParameter[] parms)
{
using (DbConnection conn = _dbFactory.CreateDbConnection())
{
using (DbCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sql;
if (parms != null)
{
cmd.Parameters.AddRange(parms);
}
return cmd.ExecuteScalar();
}
}
}

public DbParameter CreateDbParameter(string parameterName, object value)
{
return _dbFactory.CreateDbParameter(parameterName, value);
}
}

 

3.DbFactory.cs

public abstract class DbFactory
{
public abstract DbConnection CreateDbConnection();
public abstract DbParameter CreateDbParameter(string parameterName, object value);
}

 

4.SqlDbFactory.cs

public class SqlDbFactory : DbFactory
{
private static readonly string _connectionString = @"Server=.;Database=demo;uid=sa;pwd="";Trusted_Connection=True;MultipleActiveResultSets=true;";

public override DbConnection CreateDbConnection()
{
return new SqlConnection(_connectionString);
}

public override DbParameter CreateDbParameter(string parameterName, object value)
{
return new SqlParameter(parameterName, value);
}
}

 

posted on 2023-05-04 13:33  一只向上爬的小蜗牛  阅读(24)  评论(0编辑  收藏  举报