1、简单工厂模式属于类的创建模式,又称静态工厂方法模式;
2、通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都是具有共同的父类;
3、角色
3.1 工厂角色-Creator:它是简单工厂模式的核心,负责实现创建所有实例的内部逻辑,工厂类可以被外界直接调用,创建所需的产品对象;
3.2 抽象角色-Product:简单工厂模式所创建的所有对象的父类,它负责描述所有实例共有的公共接口;
3.3 具体产品-Concrete Product:简单工厂模式所创建的具体实例对象;
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFactory { public class Operation { public double NumberA { get; set; } public double NumberB { get; set; } 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 OperationMultiplication : Operation { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } public class OperationDivision : Operation { public override double GetResult() { if(NumberB==0) { throw new Exception("除数不能为0!!!记住啦"); } else { double result = 0; result = NumberA / NumberB; return result; } } } 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 OperationMultiplication(); break; case "/": oper = new OperationDivision(); break; } return oper; } } class Program { static void Main(string[] args) { Console.WriteLine("请输入第一个数字:"); double numberA = double.Parse(Console.ReadLine()); Console.WriteLine("请输入caozuofu.html" target="_blank">操作符:"); string opera = Console.ReadLine(); Console.WriteLine("请输入第二个数字"); double numberB=double.Parse(Console.ReadLine()); Operation oper = new Operation(); oper = OperationFactory.CreateOperate(opera); oper.NumberA = numberA; oper.NumberB = numberB; double result = oper.GetResult(); Console.WriteLine(result.ToString()); Console.ReadKey(); } } }
参考资料: http://visualcsharp.diandian.com/post/2012-11-05/40041450121