工厂模式-工厂方法模式

工厂方法

案例改进

定义

定义一个工厂父类,工厂父类负责定义创建对象的公共接口,而子类则负责生成具体的对象。即将类的实例化延迟到工厂类的子类中完成,即由子类来决定应该实例化哪一个类。

UML类图

优缺点

  • 优点: 符合设计原则
  • 缺点:类的个数成倍增加,增加了系统的复杂度
代码

 1.Program.cs

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

string selectSql = "select count(*) from T_Persons;";
object count = sqlHelper.ExecuteScalar(selectSql);

Console.WriteLine($"共有{count}记录");
}
}

2.SqlHelper.cs

public class SqlHelper
{
DbConnectionFactory _connectionFactory;

public SqlHelper(DbConnectionFactory connectionFactory)
{
this._connectionFactory = connectionFactory;
}

/// <summary>
/// 增删改操作,返回影响条数
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int ExecuteNonQuery(string sql)
{
using (DbConnection conn = _connectionFactory.CreateDbConnection())
{
using (DbCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sql;
return cmd.ExecuteNonQuery();
}
}
}

/// <summary>
/// 查询操作,返回查询结果中的第一行第一列的值
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public object ExecuteScalar(string sql)
{
using (DbConnection conn = _connectionFactory.CreateDbConnection())
{
using (DbCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sql;
return cmd.ExecuteScalar();
}
}
}
}

3.DbConnectionFactory.cs

public abstract class DbConnectionFactory
{
public abstract DbConnection CreateDbConnection();
}

4.SqlConnectionFactory.cs

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

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

posted on 2023-04-28 10:35  一只向上爬的小蜗牛  阅读(19)  评论(0编辑  收藏  举报