替代if else 或者 Switch 中介者模式
1.新建中介者:
public class OperateAction
{
private string _OperateObj; //操作对象
public string OperateObj
{
get { return _OperateObj; }
set { _OperateObj = value; }
}
public OperateAction(string operate)
{
this._OperateObj = operate;
}
private Dictionary<string, Action<string>> doMethod = new Dictionary<string, Action<string>>();
/// <summary>
/// 添加操作命令
/// </summary>
/// <param name="operate">操作命令</param>
/// <param name="dicActiion">注意这个Action<string> ,方法参数必须有</param>
public void GatherOperate(string operate, Action<string> dicActiion)
{
if (!doMethod.ContainsKey(operate))
{
doMethod.Add(operate, dicActiion);
}
}
/// <summary>
/// 执行操作
/// </summary>
/// <param name="_operate"></param>
public void ExeceteOperate(string _operate)
{
if (doMethod.ContainsKey(_operate))
doMethod[OperateObj](_operate);
}
}
2.调用方法
#region 每个方法
private void Insert(string operate)
{
MessageBox.Show(operate);
}
private void Edit(string operate)
{
MessageBox.Show(operate);
}
private void Update(string operate)
{
MessageBox.Show(operate);
}
private void Cancel(string operate)
{
MessageBox.Show(operate);
}
private void Delete(string operate)
{
MessageBox.Show(operate);
}
#endregion
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
string comtext = comboBox1.Text.Trim(); //命令
OperateAction OP = new OperateAction(comtext);
OP.GatherOperate(comtext, Insert);
OP.GatherOperate(comtext, Edit);
OP.GatherOperate(comtext, Update);
OP.GatherOperate(comtext, Cancel);
OP.GatherOperate(comtext, Delete);
OP.ExeceteOperate(comtext); //执行
}

浙公网安备 33010602011771号