十几年前的系统中存在一个核心字典表,对此核心字典表的操作分散到不同的代码模块中,
而且没有做代码复用,都是在各自的模块里直接操作DataTable
大体需求:
原系统代码如下(实现依次检查名字或者别名是否存在的需求,将查找到的数据创建一个新的DataTable供外部使用),不要问为啥这样写,那是一个没有Linq,不懂模式的时代,
if (s_Arry_ToValidate.Length > 0)
{
DataRow[] o_RowExist;
DataRow o_RowItem;
string s_Item_Now = string.Empty;
foreach (string s_Item in s_Arry_ToValidate)
{
s_Item_Now = s_Item.ToUpper().Trim();
o_RowNew = o_DataTable_Columns.NewRow();
o_RowExist = o_DataTable.Select("NAME='" + s_Item_Now + "'");
if (o_RowExist.Length > 0)
{
o_RowItem = o_RowExist[0];
o_RowNew[0] = o_RowItem[0];
o_RowNew[1] = o_RowItem[1].ToString();
o_RowNew[2] = o_RowItem[6];
o_RowNew[3] = o_RowItem[7];
o_DataTable_Columns.Rows.Add(o_RowNew);
continue;
}
o_RowExist = o_DataTable.Select("ALIAS_NAME1='" + s_Item_Now + "'");
if (o_RowExist.Length > 0)
{
o_RowItem = o_RowExist[0];
o_RowNew[0] = o_RowItem[0];
o_RowNew[1] = o_RowItem[1].ToString();
o_RowNew[2] = o_RowItem[6];
o_RowNew[3] = o_RowItem[7];
o_DataTable_Columns.Rows.Add(o_RowNew);
continue;
}
o_RowExist = o_DataTable.Select("ALIAS_NAME2='" + s_Item_Now + "'");
if (o_RowExist.Length > 0)
{
o_RowItem = o_RowExist[0];
o_RowNew[0] = o_RowItem[0];
o_RowNew[1] = o_RowItem[1].ToString();
o_RowNew[2] = o_RowItem[6];
o_RowNew[3] = o_RowItem[7];
o_DataTable_Columns.Rows.Add(o_RowNew);
continue;
}
o_RowExist = o_DataTable.Select("ALIAS_NAME3='" + s_Item_Now + "'");
if (o_RowExist.Length > 0)
{
o_RowItem = o_RowExist[0];
o_RowNew[0] = o_RowItem[0];
o_RowNew[1] = o_RowItem[1].ToString();
o_RowNew[2] = o_RowItem[6];
o_RowNew[3] = o_RowItem[7];
o_DataTable_Columns.Rows.Add(o_RowNew);
continue;
}
o_RowExist = o_DataTable.Select("ALIAS_NAME4='" + s_Item_Now + "'");
if (o_RowExist.Length > 0)
{
o_RowItem = o_RowExist[0];
o_RowNew[0] = o_RowItem[0];
o_RowNew[1] = o_RowItem[1].ToString();
o_RowNew[2] = o_RowItem[6];
o_RowNew[3] = o_RowItem[7];
o_DataTable_Columns.Rows.Add(o_RowNew);
continue;
}
o_RowExist = o_DataTable.Select("ALIAS_NAME5='" + s_Item_Now + "'");
if (o_RowExist.Length > 0)
{
o_RowItem = o_RowExist[0];
o_RowNew[0] = o_RowItem[0];
o_RowNew[1] = o_RowItem[1].ToString();
o_RowNew[2] = o_RowItem[6];
o_RowNew[3] = o_RowItem[7];
o_DataTable_Columns.Rows.Add(o_RowNew);
continue;
}
}
}
重构
这里面就有一个职责链的需求,先判断英文名字,存在了则返回数据,不存在则在各个别名中查找,因为此系统大部分的查找的是英文名字,所以要放到链的第一个。
假设有如下数据:
代码:
interface ICheckHandler
{
DataRow Process(EnumerableRowCollection<DataRow> allData, string name2Check);
}
class NameCheckHandler : ICheckHandler
{
public DataRow Process(EnumerableRowCollection<DataRow> allData, string name2Check)
{
var resuslt = allData.Where(item => item["NAME"].ToString().Equals(name2Check));
if (resuslt.Any())
{
return resuslt.FirstOrDefault();
}
return null;
}
}
class ALIASName1CheckHandler : ICheckHandler
{
public DataRow Process(EnumerableRowCollection<DataRow> allData, string name2Check)
{
var resuslt = allData.Where(item => item["ALIAS_NAME1"].ToString().Equals(name2Check));
if (resuslt.Any())
{
return resuslt.FirstOrDefault();
}
return null;
}
}
class ALIASName2CheckHandler : ICheckHandler
{
public DataRow Process(EnumerableRowCollection<DataRow> allData, string name2Check)
{
var resuslt = allData.Where(item => item["ALIAS_NAME2"].ToString().Equals(name2Check));
if (resuslt.Any())
{
return resuslt.FirstOrDefault();
}
return null;
}
}
class NameCheckChain
{
private List<ICheckHandler> handlers = new List<ICheckHandler>();
public void AddHandler(ICheckHandler handler)
{
handlers.Add(handler);
}
public DataRow Process(DataTable allData, string name2Check)
{
foreach (var handler in handlers)
{
DataRow result = handler.Process(allData.AsEnumerable(), name2Check);
if (result != null)
{
return result;
}
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
string[] names = { "机匣振动03", "机振05", "jxzd_01" };
List<DataRow> rows1 = GetDetails(names);
foreach (var row in rows1)
{
Console.WriteLine(string.Join(",", row.ItemArray));
}
//List<DataRow> rows2 = GetDetails2(names);
}
#region 根据任意名字找信息
//随意输入一个名称,或者别名1...别名n,找到此CHANNEL的详细定义
static List<DataRow> GetDetails(string[] names)
{
NameCheckChain nc = new NameCheckChain();
nc.AddHandler(new NameCheckHandler());
nc.AddHandler(new ALIASName1CheckHandler());
nc.AddHandler(new ALIASName2CheckHandler());
List<DataRow> result = new List<DataRow>();
DataTable dt = GetAllDatas();
foreach (string name in names)
{
var row = nc.Process(dt, name);
if (row != null)
{
result.Add(row);
}
}
return result;
}
static List<DataRow> GetDetails2(string[] names)
{
var handlers = new List<Func<EnumerableRowCollection<DataRow>, string, DataRow>>();
handlers.Add((new NameCheckHandler()).Process);
handlers.Add((new ALIASName1CheckHandler()).Process);
handlers.Add((new ALIASName2CheckHandler()).Process);
List<DataRow> result = new List<DataRow>();
var dt = GetAllDatas().AsEnumerable();
foreach (string name in names)
{
foreach (var handler in handlers)
{
var row = handler(dt, name);
if (row != null)
{
result.Add(row);
break;
}
}
}
return result;
}
static DataTable GetAllDatas()
{
DataHelper dh = new DataHelper();
string sql = @"SELECT ID,NAME,ALIAS_NAME1,ALIAS_NAME2,ALIAS_NAME3,ALIAS_NAME4 FROM 表名"; //空字符串的名字也要保留,因为别名保存的位置随机
dh.CreateCommand(sql);
return dh.selectExecute();
}
#endregion
#region 数据导入相关
static void DataImport()
{
DataTable data2Import = CSVHelper.ReadFromCSV(@"D:\ImportTemplate.csv", true);
CheckExistData(data2Import);
Insert2DB(data2Import);
}
。。。。。。
以上的实现中,并么有在ICheckHandler的实现类中定义下一个实现了ICheckHandler的链,而是通过List<ICheckHandler> handlers的方式实现了链的概念。
在GetDetails2方法中,更是将ICheckHandler的接口舍弃,直接定义了 方法链进行测试。
这里的重构也只是思考职责链的表现形式和实际的应用。
如果各个别名还有更复杂的需求,定义ICheckHandler接口肯定是最好的办法。
public class DataHelper
{
private MySqlConnection conn = null;
private MySqlCommand command = null;
private MySqlDataReader reader = null;
/// <summary>
/// 构造方法里建议连接
/// </summary>
/// <param name="connstr"></param>
public DataHelper(string connstr)
{
//我这里是在构造函数里传入mysql连接语句
conn = new MySqlConnection(connstr);
}
public DataHelper()
{
string mysqlStr = "Data Source=127.0.0.1;User Id=root;Password=;;pooling=false;CharSet=utf8;port=3306;Database=test;";
conn = new MySqlConnection(mysqlStr);
}
/// <summary>
/// 发送指令
/// </summary>
/// <param name="sql"></param>
public void CreateCommand(string sql)
{
conn.Open();
command = new MySqlCommand(sql, conn);
}
/// <summary>
/// 增、删、改公共方法
/// </summary>
/// <returns></returns>
public int commonExecute()
{
int res = -1;
try
{
res = command.ExecuteNonQuery();
}
catch (MySqlException ex)
{
Console.WriteLine("操作失败!" + ex.Message);
}
conn.Close();
return res;
}
/// <summary>
/// 查询方法
/// 注意:尽量不要用select * from table表(返回的数据过长时,DataTable可能会出错),最好指定要查询的字段。
/// </summary>
/// <returns></returns>
public DataTable selectExecute()
{
DataTable dt = new DataTable();
using (reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
dt.Load(reader);
}
return dt;
}
}
public class CSVHelper
{
public static DataTable ReadFromCSV(string path, bool hasTitle = false)
{
DataTable dt = new DataTable(); //要输出的数据表
StreamReader sr = new StreamReader(path); //文件读入流
bool bFirst = true; //指示是否第一次读取数据
//逐行读取
string line;
while ((line = sr.ReadLine()) != null)
{
string[] elements = line.Split(',');
//第一次读取数据时,要创建数据列
if (bFirst)
{
for (int i = 0; i < elements.Length; i++)
{
dt.Columns.Add();
}
bFirst = false;
}
//有标题行时,第一行当做标题行处理
if (hasTitle)
{
for (int i = 0; i < dt.Columns.Count && i < elements.Length; i++)
{
dt.Columns[i].ColumnName = elements[i];
}
hasTitle = false;
}
else //读取一行数据
{
if (elements.Length == dt.Columns.Count)
{
dt.Rows.Add(elements);
}
else
{
//throw new Exception("CSV格式错误:表格各行列数不一致");
}
}
}
sr.Close();
return dt;
}
/// <summary>
/// 将DataTable内容保存到CSV文件中
/// </summary>
/// <param name="dt">数据表</param>
/// <param name="path">CSV文件地址</param>
/// <param name="hasTitle">是否要输出数据表各列列名作为CSV文件第一行</param>
public static void SaveToCSV(DataTable dt, string path, bool hasTitle = false)
{
StreamWriter sw = new StreamWriter(path);
//输出标题行(如果有)
if (hasTitle)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i].ColumnName);
if (i != dt.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.WriteLine();
}
//输出文件内容
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
sw.Write(dt.Rows[i][j].ToString());
if (j != dt.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.WriteLine();
}
sw.Close();
}
}