29、面向对象设计模式之简单工厂模式-具体实现
基本实现:
public abstract class Product{ } public class ConcretProduct:Product{ } public class Factory{ public static Product CreateProduct(){ return new ConcretProduct(); } } class Program{ static void Main(string[] args){ Product product = Factory.CreateProduct(); Console.WriteLine("Created:{0}",product.GetType().Name); } }
简单提升
实现加减乘除未用工厂模式
public class Operation{ public static double GetResult(double numberA,double numberB, string operate){ double result = 0; switch(operate){ case "+": result = numberA + numberB; break; case "-": result = numberA - numberB; break; case "*" result = numberA * numberB; break; case "/" result = numberA / numberB; break; } return result; } } class Program{ static void Main(string[] args){ try { Console.WriteLine("输入数字:") string stringNumberA = Console.ReadLine(); Console.WriteLine("请输入运算符号: +, - *, / \n"); string stringOperate = Console.ReadLine(); Console.WriteLine("请在输入一个数:"); string stringNumberB = Console.ReadLine(); string stringResult = Convert.ToString(Operation.GetResult(Convert.ToDouble(stringNumberA), Convert.ToDouble(stringNumberB),Convert.ToString(stringOperate))); Console.WriteLine("结果是:" + stringResult); }catch(Exception ex){ Console.WriteLine("你输入有错:",ex.Message); } Operation.GetResult(2.4,2.5, "+") } }
实现加减乘除使用简单工厂模式
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; } } public class OperationAdd:Operation{ public override double GetResult{ double result = 0; result = numberA + numberB; return result; } } public class OperationSub:Operation{ public override double GetResult(){ double result = 0; result = numberA - numberB; return result; } } public class OperationMultiply:Operation{ public override double GetResult(){ double result = 0; result = numberA * numberB; return result; } } public class OperationDivide:Operation{ public override double GetResult(){ double result = 0; result = numberA / numberB; if(0==numberB){ throw new Exception("除数不能为零"); } return result; } } public class OperationFactory{ public static Operation CreateOperation(string operate){ Operation operation = null; switch(operate){ case "+": operation = new OperationAdd(); break; case "-": operation = new OperationSub(); break; case "*": operation = new OperationMultiply(); break; case "/": operation = new OperationDivide(); break; } return operation; } } class Program{ static void Main(string[] args){ Operation oper; oper = OperationFactory.CreateOperation("+"); oper.NumberA = 1; oper.NumberB = 2; oper.GetResult(); } }