工厂方法与简单工厂的区别在于工厂方法没有switch条件分支,实例化哪一个子类放到了客户端(可以利用反射),这样整个工厂和产品体系都没有修改的变化,而只是扩展的变化,这就完全符合了开放-封闭原则的精神。
工厂方法类图:
从UML图可以看出,在工厂方法模式中,工厂类与具体产品类具有平行的等级结构,它们之间是一一对应的。针对UML图的解释如下:
Creator类:充当抽象工厂角色,任何具体工厂都必须继承该抽象类
TomatoScrambledEggsFactory和ShreddedPorkWithPotatoesFactory类:充当具体工厂角色,用来创建具体产品
Food类:充当抽象产品角色,具体产品的抽象类。任何具体产品都应该继承该类
TomatoScrambledEggs和ShreddedPorkWithPotatoes类:充当具体产品角色,实现抽象产品类对定义的抽象方法,由具体工厂类创建,它们之间有一一对应的关系。
C#工厂方法:
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(); } } }
namespace 工厂方法_计算器 { 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(); } } }
总结:由于js语言特性,没有工厂模式