using System; using System.Collections.Generic; using System.Text; /* * 工厂方法模式是简单工厂模式的衍生,解决了许多简单工厂模式的问题。首先完全实现‘开-闭 原则’,实现了可扩展。 * 其次更复杂的层次结构,可以应用于产品结果复杂的场合。 * 工厂方法模式的对简单工厂模式进行了抽象。 * 有一个抽象的Factory类(可以是抽象类和接口),这个类将不再负责具体的产品生产,而是只制定一些规范,具体的生产工作由其子类去完成。 * 在这个模式中,工厂类和产品类往往可以依次对应。 * 即一个抽象工厂对应一个抽象产品,一个具体工厂对应一个具体产品,这个具体的工厂就负责生产对应的产品。 */ namespace 工厂方法_计算器 { /// <summary> /// 运算类 /// </summary> 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; } } /// <summary> /// 得到运算结果 /// </summary> /// <returns></returns> public virtual double GetResult() { double result = 0; return result; } } /// <summary> /// 加法类 /// </summary> class OperationAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } /// <summary> /// 减法类 /// </summary> class OperationSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } /// <summary> /// 乘法类 /// </summary> class OperationMul : Operation { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } /// <summary> /// 除法类 /// </summary> class OperationDiv : Operation { public override double GetResult() { double result = 0; if (NumberB == 0) throw new Exception("除数不能为0。"); result = NumberA / NumberB; return result; } } /// <summary> /// 工厂方法 /// </summary> interface IFactory { Operation CreateOperation(); } /// <summary> /// 专门负责生产“+”的工厂 /// </summary> class AddFactory : IFactory { public Operation CreateOperation() { return new OperationAdd(); } } /// <summary> /// 专门负责生产“-”的工厂 /// </summary> class SubFactory : IFactory { public Operation CreateOperation() { return new OperationSub(); } } /// <summary> /// 专门负责生产“*”的工厂 /// </summary> class MulFactory : IFactory { public Operation CreateOperation() { return new OperationMul(); } } /// <summary> /// 专门负责生产“/”的工厂 /// </summary> class DivFactory : IFactory { public Operation CreateOperation() { return new OperationDiv(); } } class Program { static void Main1(string[] args) { IFactory operFactory = new AddFactory(); Operation oper = operFactory.CreateOperation(); oper.NumberA = 1; oper.NumberB = 2; double result = oper.GetResult(); Console.WriteLine(result); Console.Read(); } } }