简单工厂模式的本质是利用多态性,将实例化的过程交给工厂去完成,减少耦合度
实现加减乘除功能的计算器:
//操作类基类 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() { return NumberA + NumberB; } } public class OperationSub : Operation { public override double GetResult() { return NumberA - NumberB; } } public class OperationMul : Operation { public override double GetResult() { return NumberA * NumberB; } } public class OperationDiv : Operation { public override double GetResult() { if (NumberB==0) { throw new Exception("除数不能为0"); } return NumberA / NumberB; } }
然后构造工厂类,根据客户端传入的参数,实例化不同的操作类,返回给调用者
public class OperationFactory { public static Operation CreateOperation(string operation) { Operation oper = null; switch (operation) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; default: oper = new Operation(); break; } return oper; } }
客户端调用时,不需要认识所有的操作类,而只需要认识操作类的基类和工厂类即可:
//乘法 Operation operMutil = OperationFactory.CreateOperation("*"); operMutil .NumberA = 3; operMutil .NumberB = 5; double mutilResult = operMutil .GetResult(); //加法 Operation operAdd = OperationFactory.CreateOperation("+"); operAdd .NumberA = 3; operAdd .NumberB = 5; double addResult = operAdd .GetResult();