delegate 模式 如何应用
private static void GetContractNode(Program p, XmlHelper xh, Hashtable htAt, Hashtable htValue, string xpathForContract)
{
ClearHt(htAt, htValue);
htAt.Add(p.GetNameStr(), p.GetContractInformation());
xh.InsertNode(p.xmlFileName, p.GetContractInfo(), true, p.GetReportInfo(), htAt, htValue);
ClearHt(htAt, htValue);
htAt.Add(p.GetNameStr(), p.GetContractNumber());
htAt.Add(p.GetTypeStr(), p.GetStringStr());
htAt.Add(p.GetValueStr(), "9");
xh.InsertNode(p.xmlFileName, p.GetParameterStr(), true, xpathForContract, htAt, htValue);
ClearHt(htAt, htValue);
htAt.Add(p.GetNameStr(), p.GetOrderType());
htAt.Add(p.GetTypeStr(), p.GetStringStr());
htAt.Add(p.GetValueStr(), "压力订单");
xh.InsertNode(p.xmlFileName, p.GetParameterStr(), true, xpathForContract, htAt, htValue);
//比如 我下面 还有1000行 与上面相同的代码 只是 htAt添加的内容不同
}
//还有个方法 也类似
private static void GetCustomerNode(Program p, XmlHelper xh, Hashtable htAt, Hashtable htValue, string xpathForCustomer)
{
ClearHt(htAt, htValue);
htAt.Add(p.GetNameStr(), p.GetCustomerInformation());
xh.InsertNode(p.xmlFileName, p.GetCustomerInfo(), true, p.GetReportInfo(), htAt, htValue);
ClearHt(htAt, htValue);
htAt.Add(p.GetNameStr(), p.GetCustomerName());
htAt.Add(p.GetTypeStr(), p.GetStringStr());
htAt.Add(p.GetValueStr(), "压力哥");
xh.InsertNode(p.xmlFileName, p.GetParameterStr(), true, xpathForCustomer, htAt, htValue);
//比如 我下面 还有1000行 与上面相同的代码 只是 htAt添加的内容不同
}
这2个方法 看起来结构类似 传递的参数 内容不一样 ,还有方法内部的实现 好多看起来重复的。。我要怎么重构模式呢。。 我想不出好的办法, 请高手指点
------解决方案--------------------
如果代码结构类似,只是方法不同(方法签名相同),可以通过委托把方法传进来。
我给你写了个Demo,你看看。
public class DelegateTest
{
public delegate string OperationHandle(Entity entity);
public void DelegateOperation(OperationHandle operation1, OperationHandle operation2, Hashtable hashTable, List<Entity> entityList)
{
if (entityList != null && entityList.Count > 0)
{
for (int i = 0; i < entityList.Count; i++)
{
hashTable.Add(operation1(entityList[i]), operation2(entityList[i]));
}
}
}
public string GetName(Entity entity)
{
return entity.Name;
}
public string GetMemo(Entity entity)
{
return entity.Memo;
}
public class Entity
{
public string Name { get; set; }
public string Memo { get; set; }
}
public static void Main()
{
List<Entity> entityList = new List<Entity>();
for (int i = 0; i < 10; i++)
{
Entity entity = new Entity();
entity.Name = "Name" + i;
entity.Memo = "Memo" + i;
entityList.Add(entity);
}
Hashtable hashTable = new Hashtable();
DelegateTest test = new DelegateTest();
OperationHandle op1 = new OperationHandle(test.GetName);
OperationHandle op2 = new OperationHandle(test.GetMemo);
test.DelegateOperation(op1, op2, hashTable, entityList);
}
}