Skip to content

工厂模式是什么

工厂模式概述

  • 定义
  • 工厂模式是一种 创建型设计模式,通过工厂类封装对象创建逻辑,客户端无需直接使用 new 构造对象,而是通过工厂方法或接口获取实例。
  • 核心思想
  • 将对象的创建与使用分离,降低耦合,增强扩展性。
  • 分类
  • 简单工厂(非 GoF 23 种,变种)。
  • 工厂方法(Factory Method)。
  • 抽象工厂(Abstract Factory)。

核心点

  • 工厂模式通过工厂类统一创建对象,Spring 的 BeanFactory 是典型应用。

1. 工厂模式核心概念

(1) 角色

  • 产品接口(Product)
  • 定义对象的抽象接口。
  • 例:interface Product
  • 具体产品(Concrete Product)
  • 实现产品接口的类。
  • 例:ConcreteProductA
  • 工厂(Factory)
  • 负责创建产品实例。
  • 例:FactoryConcreteFactory
  • 客户端(Client)
  • 通过工厂获取产品。

(2) 优势

  • 解耦:客户端不直接依赖具体类。
  • 扩展性:新增产品只需加工厂或实现。
  • 统一管理:集中创建逻辑。

(3) 图示

[Client] --> [Factory] --> [Product]
                        --> [ConcreteProductA]
                        --> [ConcreteProductB]

2. 工厂模式的分类与实现

(1) 简单工厂(Simple Factory)

  • 定义
  • 通过一个工厂类,根据参数创建不同产品。
  • 不属于 GoF 23 种,但常用。
  • 代码示例
// 产品接口
public interface Product {
    void use();
}

// 具体产品
public class ProductA implements Product {
    @Override
    public void use() {
        System.out.println("Using ProductA");
    }
}

public class ProductB implements Product {
    @Override
    public void use() {
        System.out.println("Using ProductB");
    }
}

// 简单工厂
public class SimpleFactory {
    public static Product createProduct(String type) {
        if ("A".equals(type)) {
            return new ProductA();
        } else if ("B".equals(type)) {
            return new ProductB();
        }
        return null;
    }
}

// 客户端
public class Client {
    public static void main(String[] args) {
        Product product = SimpleFactory.createProduct("A");
        product.use(); // 输出: Using ProductA
    }
}
  • 特点
  • 简单,但违反开闭原则(新增产品需改工厂代码)。
  • 场景
  • 产品种类固定,扩展少。

(2) 工厂方法(Factory Method)

  • 定义
  • 定义创建产品的接口,子类工厂实现具体创建逻辑。
  • 代码示例
// 产品接口
public interface Product {
    void use();
}

// 具体产品
public class ProductA implements Product {
    @Override
    public void use() {
        System.out.println("Using ProductA");
    }
}

// 工厂接口
public interface Factory {
    Product createProduct();
}

// 具体工厂
public class FactoryA implements Factory {
    @Override
    public Product createProduct() {
        return new ProductA();
    }
}

// 客户端
public class Client {
    public static void main(String[] args) {
        Factory factory = new FactoryA();
        Product product = factory.createProduct();
        product.use(); // 输出: Using ProductA
    }
}
  • 特点
  • 符合开闭原则,新增产品只需加工厂。
  • 每个产品对应一个工厂。
  • 场景
  • 产品种类较多,需扩展。

(3) 抽象工厂(Abstract Factory)

  • 定义
  • 提供创建一系列相关产品族的接口,无需指定具体类。
  • 代码示例
// 抽象产品接口
public interface Button {
    void render();
}

public interface Text {
    void display();
}

// 具体产品
public class WindowsButton implements Button {
    @Override
    public void render() {
        System.out.println("Windows Button");
    }
}

public class WindowsText implements Text {
    @Override
    public void display() {
        System.out.println("Windows Text");
    }
}

public class MacButton implements Button {
    @Override
    public void render() {
        System.out.println("Mac Button");
    }
}

public class MacText implements Text {
    @Override
    public void display() {
        System.out.println("Mac Text");
    }
}

// 抽象工厂
public interface UIFactory {
    Button createButton();
    Text createText();
}

// 具体工厂
public class WindowsFactory implements UIFactory {
    @Override
    public Button createButton() {
        return new WindowsButton();
    }

    @Override
    public Text createText() {
        return new WindowsText();
    }
}

public class MacFactory implements UIFactory {
    @Override
    public Button createButton() {
        return new MacButton();
    }

    @Override
    public Text createText() {
        return new MacText();
    }
}

// 客户端
public class Client {
    public static void main(String[] args) {
        UIFactory factory = new WindowsFactory();
        Button button = factory.createButton();
        Text text = factory.createText();
        button.render(); // 输出: Windows Button
        text.display();  // 输出: Windows Text
    }
}
  • 特点
  • 创建产品族(如 UI 组件)。
  • 新增产品族简单,新增产品类型复杂。
  • 场景
  • 系统需支持多套相关对象(如不同主题的 UI)。

3. 工厂模式在 Spring 中的应用

  • 结合您的问题(Spring AOP、代理模式):
  • BeanFactory
    • Spring 的核心接口,工厂模式的典型实现。
    • 例:ApplicationContext 创建 Bean。
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = context.getBean("userService", UserService.class);
  • ObjectFactory
    • 用于延迟创建 Bean(如循环依赖的三级缓存,您提问)。
  • FactoryBean
    • 自定义 Bean 创建逻辑。
@Component
public class CustomFactoryBean implements FactoryBean<Product> {
    @Override
    public Product getObject() {
        return new ProductA();
    }

    @Override
    public Class<?> getObjectType() {
        return Product.class;
    }
}
  • AOP 代理
    • Spring 使用工厂(如 ProxyFactory)生成代理对象。
  • 与 RESTful API
  • 工厂模式可创建 API 处理器:
public interface ApiHandler {
    void handle();
}

public class UserApiHandler implements ApiHandler {
    @Override
    public void handle() {
        System.out.println("Handle user API");
    }
}

@Component
public class ApiHandlerFactory {
    public ApiHandler createHandler(String type) {
        if ("user".equals(type)) {
            return new UserApiHandler();
        }
        return null;
    }
}

4. 使用场景

  • 复杂对象创建
  • 如数据库连接池(DataSource)。
  • 多实现切换
  • 如支付方式(支付宝、微信)。
  • 框架开发
  • Spring 的 Bean 创建。
  • 插件系统
  • 动态加载模块。
  • UI 组件
  • 不同风格的按钮、窗口。

与您的问题

  • Spring AOP
  • ProxyFactory 创建代理对象。
  • 单点登录
  • 工厂创建认证处理器(如 JWT、OAuth)。
  • 事务传播
  • 工厂生成事务管理器。

5. 优缺点

优点

  • 解耦
  • 客户端不关心具体类。
  • 扩展性
  • 新增产品只需加工厂。
  • 统一管理
  • 集中创建逻辑。

缺点

  • 复杂性
  • 工厂方法为每产品加类。
  • 代码量
  • 抽象工厂增加维护成本。
  • 简单工厂局限
  • 违反开闭原则。

6. 工厂模式 vs 其他模式

工厂方法 vs 抽象工厂

特性 工厂方法 抽象工厂
粒度 单一产品 产品族
扩展 加子工厂 加工厂和产品族
复杂度 简单 复杂

工厂模式 vs 单例

  • 工厂:创建多实例或类型。
  • 单例:确保单一实例。

工厂模式 vs 建造者

  • 工厂:关注创建对象。
  • 建造者:关注复杂对象组装。

7. 最佳实践

  • 选择类型
  • 简单场景用简单工厂。
  • 扩展频繁用工厂方法。
  • 产品族用抽象工厂。
  • 命名清晰
  • UserFactoryOrderApiFactory
  • 异常处理
  • 工厂方法抛出明确异常。
  • Spring 集成
  • FactoryBean@Bean

8. 延伸与面试角度

  • 与 Spring
  • BeanFactoryFactoryBean 是工厂模式。
  • 与代理模式
  • 工厂生成代理对象(如 AOP)。
  • 与 RESTful API
  • 工厂创建 API 处理器。
  • 实际应用
  • 电商:支付工厂(支付宝、微信)。
  • 微服务:动态服务工厂。
  • 面试点
  • 问“定义”时,提三类工厂。
  • 问“场景”时,提 Spring 示例。

9. 总结

工厂模式通过工厂类封装对象创建,包括简单工厂、工厂方法和抽象工厂,解耦客户端和具体类。Spring 的 BeanFactory 和 AOP 代理是典型应用。结合您的问题,工厂可创建 SSO 认证器或 API 处理器。面试时,可提代码、Spring 案例或与代理模式的对比,展示理解深度。


如果您想深入某类型工厂(如抽象工厂代码)或具体场景,请告诉我,我可以进一步优化!