工厂模式

设计模式 设计模式
📅 2025-07-25 15:38 👤 admin

工厂模式是一种创建对象的设计模式,它将对象的创建和使用分离,使得代码更加灵活、可维护和可扩展。这种模式特别适用于以下场景:
  • 当一个类不知道它所必须创建的对象的类时
  • 当一个类希望由它的子类来指定所创建的对象时
  • 当将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化时
    using System;
    
    // 定义产品接口
    public interface IProduct
    {
        void Operation();
    }
    
    // 具体产品A
    public class ConcreteProductA : IProduct
    {
        public void Operation()
        {
            Console.WriteLine("ConcreteProductA Operation");
        }
    }
    
    // 具体产品B
    public class ConcreteProductB : IProduct
    {
        public void Operation()
        {
            Console.WriteLine("ConcreteProductB Operation");
        }
    }
    
    // 简单工厂类
    public class SimpleFactory
    {
        public static IProduct CreateProduct(string type)
        {
            switch (type.ToLower())
            {
                case "a":
                    return new ConcreteProductA();
                case "b":
                    return new ConcreteProductB();
                default:
                    throw new ArgumentException("Invalid product type", nameof(type));
            }
        }
    }
    
    // 客户端代码
    class Program
    {
        static void Main()
        {
            // 使用简单工厂创建产品A
            IProduct productA = SimpleFactory.CreateProduct("A");
            productA.Operation();
    
            // 使用简单工厂创建产品B
            IProduct productB = SimpleFactory.CreateProduct("B");
            productB.Operation();
    
            try
            {
                // 尝试创建无效产品类型
                IProduct invalidProduct = SimpleFactory.CreateProduct("C");
                invalidProduct.Operation();
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }    

 

工厂模式的优点

  • 解耦对象的创建和使用:客户端不需要知道具体产品类的类名,只需要知道对应的参数即可。
  • 可扩展性好:在增加新的产品类时,只需要修改工厂类或者扩展工厂子类,符合开闭原则。
  • 便于代码维护:创建对象的逻辑集中在一个工厂类中,便于维护和修改。

工厂模式的缺点

  • 工厂类职责过重:简单工厂模式中,工厂类集中了所有产品的创建逻辑,一旦不能正常工作,整个系统都会受到影响。
  • 增加系统复杂度:如果产品种类过多,会导致工厂类变得庞大,增加系统的复杂度。
  • 违反开闭原则:在简单工厂模式中,每当增加新的产品时,都需要修改工厂类,这违反了开闭原则。

 

工厂模式在实际开发中应用广泛,特别是在需要创建大量对象、对象创建过程复杂或者需要根据不同条件创建不同类型对象的场景中。