标签:
学习正式的设计模式前,先来个开胃菜,即简单工厂模式。下面将利用简单工厂模式设计一个计算器小程序:
一、运算基类(Operation)
1 public abstract class Operation 2 { 3 public double NumA { set; get; } 4 public double NumB { set; get; } 5 public virtual double GetResult() 6 { 7 return 0; 8 } 9 }
二、运算方法(+、-)
1 public class OperationAdd : Operation 2 { 3 public override double GetResult() 4 { 5 double res = 0; 6 res = base.NumA + base.NumB; 7 return res; 8 } 9 } 10 11 public class OperationSub : Operation 12 { 13 public override double GetResult() 14 { 15 double res = 0; 16 res = base.NumA - base.NumB; 17 return res; 18 } 19 }
三、对象创建类
1 public class OperationFactory 2 { 3 public Operation CreateOperation(string op) 4 { 5 Operation res = null; 6 switch (op) 7 { 8 case "+": 9 res = new OperationAdd(); 10 break; 11 case "-": 12 res = new OperationSub(); 13 break; 14 } 15 return res; 16 } 17 }
四、执行
1 /// <summary> 2 /// 简单工厂模式 - 将实例的选择放在了工厂类中 3 /// </summary> 4 public class DoSimpleFactory : DesignPattern 5 { 6 public override void ExeFun() 7 { 8 Console.WriteLine("请输入运算符:+、-、*、/"); 9 Operation ot = new OperationFactory().CreateOperation(Console.ReadLine()); 10 ot.NumA = 2; 11 ot.NumB = 4; 12 double res = ot.GetResult(); 13 Console.Write(string.Format("计算结果为:{0}", res)); 14 } 15 }
标签:
原文地址:http://www.cnblogs.com/pasture-code/p/4560428.html