工厂方法模式(Factory Method):定义了一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到子类。
工厂方法模式在实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还存在,也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行。想要加功能,本来是修改工厂类的,而现在是修改客户端。
示例代码:
Operaction.cs
namespace 工厂方法模式 { public class Operaction { 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; } } /// <summary> /// 加 /// </summary> class OperactionAdd : Operaction { /// <summary> /// 运算方法 /// </summary> /// <returns></returns> public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } /// <summary> /// 减 /// </summary> class OperactionSub : Operaction { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } /// <summary> /// 乘 /// </summary> class OperactionMul : Operaction { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } /// <summary> /// 除 /// </summary> class OperactionDiv : Operaction { public override double GetResult() { double result = 0; result = NumberA / NumberB; return result; } } }
namespace 工厂方法模式 { /* * 总结来说,下面的1个接口四个类实现的就是简单工厂中switch的功能 */ /// <summary> /// 工厂接口 /// </summary> interface IFactory { Operaction CreateOperaction(); } /// <summary> /// 加法工厂 /// </summary> class AddFactory : IFactory { public Operaction CreateOperaction() { return new OperactionAdd(); } } /// <summary> /// 减法工厂 /// </summary> class SubFactory : IFactory { public Operaction CreateOperaction() { return new OperactionSub(); } } /// <summary> /// 乘法工厂 /// </summary> class MulFactory : IFactory { public Operaction CreateOperaction() { return new OperactionMul(); } } /// <summary> /// 除法工厂 /// </summary> class DivFactory : IFactory { public Operaction CreateOperaction() { return new OperactionDiv(); } } /// <summary> /// 客户端调用 /// </summary> class Program { static void Main(string[] args) { IFactory opfactory = new AddFactory();//这里注意,使用什么工厂,又客户端决定 Operaction oper = opfactory.CreateOperaction(); oper.NumberA = 1; oper.NumberB = 2; double res = oper.GetResult(); Console.WriteLine("计算结果:" + res); Console.ReadKey(); } } }