简单工厂模式结构图:
简单工厂模式以简单的加减乘除运算为例:
运算符类(Operation):
namespace CalcTest.Simple_Factory_patterns { 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; } } }
加法类(Add):继承于运算符类(Operation)
1 namespace CalcTest.Simple_Factory_patterns 2 { 3 class Add :Operation 4 { 5 public override double GetResult() 6 { 7 return NumberA + NumberB; 8 } 9 } 10 }
减法类(Subtraction):继承于运算符类(Operation)
1 namespace CalcTest.Simple_Factory_patterns 2 { 3 class Subtraction : Operation 4 { 5 public override double GetResult() 6 { 7 return NumberA - NumberB; 8 } 9 } 10 }
乘法类(Multiplacation):继承于运算符类(Operation)
1 namespace CalcTest.Simple_Factory_patterns 2 { 3 class Multiplication : Operation 4 { 5 public override double GetResult() 6 { 7 return NumberA * NumberB; 8 } 9 } 10 }
除法类(Division):继承于运算符类(Operation)
1 namespace CalcTest.Simple_Factory_patterns 2 { 3 class Division : Operation 4 { 5 public override double GetResult() 6 { 7 if (NumberB == 0) 8 { 9 throw new Exception("除数不能为0"); 10 } 11 return NumberA / NumberB; 12 } 13 } 14 }
运算符工厂类(OperationFactory):实例合适的对象,通过多态返回父类的方式实现计算结果
1 namespace CalcTest.Simple_Factory_patterns 2 { 3 class OperationFactory 4 { 5 public static Operation createOperation(string operate) 6 { 7 Operation oper = null; 8 switch (operate) 9 { 10 case "+": 11 oper = new Add(); 12 break; 13 case "-": 14 oper = new Subtraction(); 15 break; 16 case "*": 17 oper = new Multiplication(); 18 break; 19 case "/": 20 oper = new Division(); 21 break; 22 } 23 return oper; 24 } 25 } 26 }
测试类(Main):
1 namespace CalcTest.Simple_Factory_patterns 2 { 3 class TestMain 4 { 5 public static void Main(string[] args) 6 { 7 Operation oper = null; 8 //先输入操作符利用简单工厂模式创建类 9 Console.Write("请输入操作符:(+、-、*、/)"); 10 string operate = Console.ReadLine(); 11 oper = OperationFactory.createOperation(operate); 12 13 Console.Write("请输入数字A:"); 14 oper.NumberA = Convert.ToDouble(Console.ReadLine()); 15 16 Console.Write("请输入数字B:"); 17 oper.NumberB = Convert.ToDouble(Console.ReadLine()); 18 double result = oper.GetResult(); 19 Console.WriteLine("结果为:" + result); 20 Console.ReadLine(); 21 } 22 } 23 }
简单工厂模式操作结束!
要么忍,要么狠,要么滚!