工厂模式与工厂方法模式 - 创建型模式的巧妙设计
在软件设计中,工厂模式和工厂方法模式是两种创建型设计模式,它们都旨在解决对象的创建问题。本文将深入讨论工厂模式和工厂方法模式的概念、应用场景以及实际代码示例。
工厂模式
工厂模式是一种创建型设计模式,它提供了一个通用的接口来创建对象,但具体的实例化过程由子类决定。这样的设计允许一个类在运行时确定实例化哪个具体类,而不是在编译时进行硬编码。
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| public class 简单工厂模式 { [Fact] public void Test() { Operation oper; oper = OperationFactory.CreateOperation("+"); oper.numberA = 1; oper.numberB = 2; double result = oper.GetResult(); }
public class OperationFactory { public static Operation CreateOperation(string operat) { Operation oper = null; switch (operat) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; } return oper; } }
public class Operation { public double numberA { get; set; } public double numberB { get; set; } public virtual double GetResult() { double result = 0; return result; } } private class OperationAdd : Operation { public override double GetResult() { double result = numberA + numberB; return result; } } private class OperationSub : Operation { public override double GetResult() { double result = numberA - numberB; return result; } } }
|
工厂方法模式
工厂方法模式是工厂模式的一种变体,它通过将创建产品的方法延迟到子类来实现。每个具体工厂类都负责创建一种具体产品,从而使得系统更具可扩展性。
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
public class 工厂方法模式 { [Fact] public void Test() { IFactory factory = new AddFactory(); Operation oper = factory.CreateOperation(); oper.numberA = 1; oper.numberB = 2; double result = oper.GetResult(); } class Operation { 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 = numberA + numberB; return result; } } interface IFactory { Operation CreateOperation(); } class AddFactory : IFactory { public Operation CreateOperation() { return new OperationAdd(); } } }
|
工厂模式和工厂方法模式的应用场景
它所需要的对象的类,但知道需要某个类来创建对象时,可以使用工厂方法模式。例如,需要在运行时决定创建哪个日志记录器。
工厂方法的意图非常明确,它把类的实例化过程延迟到子类,将new()的工作交给工厂完成。同时,增加一个抽象的工厂定义,解决一系列具有统一通用工厂方法的实体工厂问题。在.NET 平台中,我们可以借助配置、泛型和委托的方法在实现经典模式目的的同时,获得工厂类型与客户程序间更加松散的构造过程。
总结
工厂模式和工厂方法模式都是创建型设计模式,它们通过将对象的创建过程封装在工厂中,提高了代码的灵活性和可维护性。选择使用哪种模式取决于具体的需求和设计情景。这两种模式在实际开发中被广泛应用,能够有效地组织和管理对象的创建过程。