3.Factory Method 工厂方法模式(创建型模式)
1.定义:
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使得一个类的实例化延迟到子类。
2.实现代码如下:
/// <summary> /// 工厂方法 /// </summary> public abstract class Factory { public abstract Compute GetCompute(); } public class AddFactory : Factory { public override Compute GetCompute() { return new AddCompute(); } } public class JianFaFactory : Factory { public override Compute GetCompute() { return new SubCompute(); } } public class ChengFaFactory : Factory { public override Compute GetCompute() { return new ChengFaCompute(); } } public class ChuFaFactory : Factory { public override Compute GetCompute() { return new ChuFaCompute(); } } /// <summary> /// 计算类 /// </summary> public abstract class Compute { protected int number1; public int Number1 { get { return number1; } set { number1 = value; } } protected int number2; public int Number2 { get { return number2; } set { number2 = value; } } public abstract int GetResult(); } /// <summary> /// 加法 /// </summary> public class AddCompute : Compute { public override int GetResult() { return number1 + number2; } } /// <summary> /// 减法 /// </summary> public class SubCompute : Compute { public override int GetResult() { return number1 - number2; } } /// <summary> /// 乘法 /// </summary> public class ChengFaCompute : Compute { public override int GetResult() { return number1 * number2; } } /// <summary> /// 除法 /// </summary> public class ChuFaCompute : Compute { public override int GetResult() { return number1 / number2; } }
static void Main(string[] args) { int number1 = 1; int number2 = 2; Factory factory = null; string operate = "+"; switch (operate) { case "+": factory = new AddFactory(); break; case "-": factory = new JianFaFactory(); break; case "*": factory = new ChengFaFactory(); break; case "/": factory = new ChuFaFactory(); break; default: break; } Compute compute = factory.GetCompute(); compute.Number1 = number1; compute.Number2 = number2; Console.WriteLine(compute.GetResult()); Console.ReadKey(); }
3.和简单工厂不同的地方是
(1)简单工厂是由switch直接创建具体的产品对象,而工厂方法是swith延迟创建具体的产品对象,先创建相应的工厂,在延迟创建具体的产品对象
(2)简单工厂只能创建一个工厂,工厂方法可以创建多个工厂
4.工厂方法的好处:
(1)用工厂方法在一个类的内部创建对象通常比直接创建对象更灵活。
(2)Factory Method模式通过面向对象的手法,将所要创建的具体对象的创建工作延迟到了子类,从而提供了一种扩展的策略,较好的解决了这种紧耦合的关系。