简单工厂模式实现计算器功能:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 简单工厂模式 { class Program { static void Main(string[] args) { Operation operation = OperationFactory.CreateOperation("/"); operation.param1 = 4; operation.param2 = 0; Console.WriteLine(operation.GetResult()); Console.ReadKey(); } /// <summary> /// 操作类的父类 /// </summary> public abstract class Operation { public double param1 { get; set; } public double param2 { get; set; } public abstract double GetResult(); } /// <summary> /// 加法类 /// </summary> public class AddOperation:Operation { public override double GetResult() { return param1 + param2; } } /// <summary> /// 减法类 /// </summary> public class MinusOperation:Operation { public override double GetResult() { return param1 - param2; } } /// <summary> /// 乘法类 /// </summary> public class MulOperation:Operation { public override double GetResult() { return param1 * param2; } } /// <summary> /// 除法类 /// </summary> public class DelOperation:Operation { public override double GetResult() { if(param2==0) { throw new Exception("除数不能为0"); } return param1 / param2; } } /// <summary> /// 工厂类,管理所有的操作,并且向外提供访问的方法 /// </summary> public class OperationFactory { /// <summary> /// 根据用户提供的操作符去创建对应的类 /// </summary> /// <param name="operationName"></param> /// <returns></returns> public static Operation CreateOperation(string operationName) { Operation operation = null; switch(operationName) { case "+": operation = new AddOperation(); break; case "-": operation = new MinusOperation(); break; case "*": operation = new MulOperation(); break; case "/": operation = new DelOperation(); break; } return operation; } } } }