定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延续到其子类中。
工厂方法模式是简单工厂的扩展,工厂方法把简单工厂的内部逻辑判断转移到了客户端进行,想要增加功能,以前是修改工厂类,现在是修改客户端。
工厂方法模式克服了简单工厂违背开放-封闭原则(软件实体应该可以扩展,但是不可以修改)的缺点,又保持了封装对象创建过程的优点。但缺点是每加一个产品,就需要加一个产品工厂的类,增加额外的开发。
public class Operation { private double _numberA = 0; private double _numberB = 0; public double NumberA { get; set; } public double NumberB { get; set; } public virtual double GetResult() { double result = 0; return result; } } class OperationAdd:Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } class OperationSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } interface IFactory { Operation CreateOperation(); } class AddFactory:IFactory { public Operation CreateOperation() { return new OperationAdd(); } } class DivFactory { public Operation CreateOperation() { return new OperationDiv(); } } //以下是客户端内代码 static void Main(string[] args) { IFactory operFactory = new AddFactory();//工厂方法模式 Operation oper = operFactory.CreateOperation(); oper.NumberA = 4; oper.NumberB = 2; double result = oper.GetResult(); Console.WriteLine(result); Console.Read(); }View Code
UML类图