你肯定遇见过这样类似的代码:
if (arg < 10) { } else if (arg >= 10 && arg < 20) { } else if (arg >= 20 && arg < 30) { } // ...... else { }
过多的if else在代码的阅读和拓展时,会变得相当的困难.
所以运用职责链模式进行分解
职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个对象练成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
代码如下:
先建立一个抽象类:
public abstract class AbsCondition<T> { protected abstract string Flag { get; } protected AbsCondition<T> condition; protected Predicate<T> conditionFunc; public void AddCondtion(AbsCondition<T> condition) { this.condition = condition; } public void HandleCondition(T obj) { if (conditionFunc(obj)) { Console.WriteLine($"{Flag},传入参数{obj}"); } else { condition?.HandleCondition(obj); } } }
再把需要处理的条件封装成对象:
public class Condition1<T> : AbsCondition<T> { public Condition1(Predicate<T> conditionFunc) { this.conditionFunc = conditionFunc; } protected override string Flag { get { return "第一个条件"; } } } public class Condition2<T> : AbsCondition<T> { public Condition2(Predicate<T> conditionFunc) { this.conditionFunc = conditionFunc; } protected override string Flag { get { return "第二个条件"; } } } public class Condition3<T> : AbsCondition<T> { public Condition3(Predicate<T> conditionFunc) { this.conditionFunc = conditionFunc; } protected override string Flag { get { return "第三个条件"; } } } public class Condition4<T> :AbsCondition<T> { public Condition4(Predicate<T> conditionFunc) { this.conditionFunc = conditionFunc; } protected override string Flag { get { return "第四个条件"; } } }
调用:
static void Main(string[] args) { try { Console.WriteLine("输入数字:"); var arg = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("=".PadRight(50,‘=‘)); Condition1<int> c1 = new Condition1<int>(x => x < 10); Condition2<int> c2 = new Condition2<int>(x => x >= 10 && x < 20); Condition3<int> c3 = new Condition3<int>(x => x >= 20 && x < 30); Condition4<int> c4 = new Condition4<int>(x => x >= 30); c1.AddCondtion(c2); c2.AddCondtion(c3); c3.AddCondtion(c4); c1.HandleCondition(arg); } catch { Console.WriteLine("发生错误,请重新输入"); } finally { Main(args); } }
拓展至 http://blog.csdn.net/laner0515/article/details/7383872"