一、前言
工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
二、工厂方法模式结构图
三、实例代码
1.1运算类
/// <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; } }
1.2工厂方法
/// <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(); } }
1.3客户端调用
class Program { static void Main(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(); } }
四、简单工厂和工厂方法的比较
客户端需要判断,就用简单工厂,如在客户端经过下拉列表选择运算符号传入工厂创建函数的参数中。
客户端不需要判断,就用工厂方法,如客户端此时知道自己要创建哪个具体的类。
简单工厂模式最大的优点是在工厂中包含了必要的逻辑判断,根据客户端的条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。但是你增加一个“求M数的N次方”的方法,我们就必须在运算工厂类中参加一个case的判断,修改了原有的类,这个就相当于违背了开放-封闭的原则。所以用到了工厂方法就不用修改原来的类,直接为新功能作扩展。
时间: 2024-11-08 23:14:32