using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory { /// <summary> /// 抽象父类 /// </summary> public class Operation { private double numberA = 0; private double numberB = 0; public double NumberA { get { return numberA; } set { numberA = value; } } public double NumberB { get { return numberB; } set { numberB = value; } } public virtual double GetResult() { double result = 0; return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory { /// <summary> /// 简单工厂模式 /// </summary> public class OperationFactory { public static Operation CreateOperate(string operate) { Operation oper = null; switch (operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; } return oper; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory { public class OperationAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory { public class OperationSub:Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory { public class OperationMul:Operation { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory { public class OperationDiv:Operation { public override double GetResult() { double result = 0; if (NumberB == 0) { throw new Exception("除数不能为0"); } result = NumberA / NumberB; return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory { class Program { static void Main(string[] args) { Console.Write("请输入数字A:"); string numberA = Console.ReadLine(); Console.Write("请输入运算符号(+,-,*,/):"); string strOperate = Console.ReadLine(); Console.Write("请输入数字B:"); string numberB = Console.ReadLine(); Operation oper; oper = OperationFactory.CreateOperate(strOperate); oper.NumberA = Convert.ToDouble(numberA); oper.NumberB = Convert.ToDouble(numberB); double result = oper.GetResult(); Console.Write("计算结果是:" + result.ToString()); Console.ReadLine(); } } }
原文:http://www.cnblogs.com/rinack/p/5254240.html