工厂模式-抽象工厂模式

定义

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

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   一只向上爬的小蜗牛  阅读(26)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示