简单工厂
简单工厂的意图在于:抽象出了公共部分,独立出每一个方法继承自父类,降低每一个方法之间的耦合度,并且防止了新增or修改方法类带来的代码错误,
前端只需要传入的运算规则即可得到结果
抽象实体
1 public class Operation 2 { 3 public double numberA { get; set; } 4 public double numberB { get; set; } 5 public virtual double GetResult() { 6 double result = 0; 7 return result; 8 } 9 10 }
独立的方法实现
1 public class OperationAdd:Operation 2 { 3 public override double GetResult() 4 { 5 double result=0d; 6 result = numberA + numberB; 7 return result; 8 } 9 } 10 11 public class OperationSub : Operation 12 { 13 public override double GetResult() 14 { 15 double result = 0d; 16 result = numberA - numberB; 17 return result; 18 } 19 }
工厂构造器
1 public class OperationFactory 2 { 3 public static Operation createOperation(string operat) { 4 Operation oper = null; 5 switch (operat) 6 { 7 case "+": 8 oper = new OperationAdd(); 9 break; 10 case "-": 11 oper = new OperationSub(); 12 break; 13 14 default: 15 16 break; 17 } 18 return oper; 19 } 20 }
UI界面
1 static void Main(string[] args) 2 { 3 Operation oper = null; 4 oper = OperationFactory.createOperation("+"); 5 oper.numberA = 2; 6 oper.numberB = 10; 7 double result=oper.GetResult(); 8 Console.WriteLine(result); 9 Console.ReadKey(); 10 }
作者:大胖儿在努力
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。