条件语句的作用是更改控制流,任何程序都离不开条件判断。但条件判断会增加程序的复杂度,过多的条件判断会导致循环复杂度(Cyclomatic Complexity)。 这种复杂度取决于3个因素: 分支变量数 分支数 条件嵌套深度 if else if else if else if switch case 1: ... case 2: ... end switch ...... end if end if end if end if 这种形状也叫 Arrow Anti Pattern。它不仅降低程序的可读性,难以扩展和重用,还会轻易地隐藏许多bug。是我们必须避免的代码。 设计模式注重于软件的重用性和扩展性,但大多数模式都可以用来降低循环复杂度。设计模式可以让不同参与者分担这些条件语句,每个参与者解决一部分问题,这样控制流程就更简单,从而降低他们的循环复杂性。 这里介绍一个用策略(Strategy)设计模式来降低循环复杂度的例子。 假设现在我们可以用 C# 写一个简单的计算器,代码如下: using System; public class Calculator { public double Calculate(double operand1, double operand2, char operater) { double result = 0.0; switch (operater) { case '+': result = operand1 + operand2; break; case '-': result = operand1 - operand2; break; case '*': result = operand1 * operand2; break; case '/': if (Math.Abs(operand2) > 0.0) { result = operand1 / operand2; } else { throw new ArithmeticException("分母为零。"); } break; default: throw new ArgumentException("未知运算符: " + operater); } return result; } public static void Main(String[] args) { args = new[] { "2", "*", "3" }; double operand1 = Double.Parse(args[0]); double operand2 = Double.Parse(args[2]); char operater = args[1][0]; double result = new Calculator().Calculate(operand1, operand2, operater); Console.WriteLine(operand1 + args[1] + operand2 + " = " + result); Console.ReadKey(); } } 现在用策略模式来重构这段代码: 模式角色: Strategy: IProcessor ConcreteStrategy: Adder, Subtractor, Multiplier, Divider Context: Calculator using System; using System.Collections.Generic; public interface IProcessor { double Process(double operand1, double operand2); } public class Adder : IProcessor { public double Process(double operand1, double operand2) { return operand1 + operand2; } } public class Subtractor : IProcessor { public double Process(double operand1, double operand2) { return operand1 - operand2; } } public class Multiplier : IProcessor { public double Process(double operand1, double operand2) { return operand1 * operand2; } } public class Divider : IProcessor { public double Process(double operand1, double operand2) { double…