【设计模式】工厂模式详解-----简单工厂模式、工厂方法模式、抽象工厂模式

工厂模式详解

一、概述

工厂模式(Factory Pattern) 是一种 创建型设计模式 ,用于 封装对象的创建逻辑 ,避免在代码中直接实例化对象,从而提高代码的 可维护性、扩展性和解耦性


二、工厂模式分类

工厂模式包括 简单工厂模式、工厂方法模式、抽象工厂模式,它们的扩展性和复杂度逐步递进:

设计模式 主要特点 适用场景 代码复杂度 是否符合开闭原则
简单工厂模式 由一个工厂类创建对象 对象种类少,变化不大 ⭐⭐ ❌ 否
工厂方法模式 每个产品有自己的工厂类 对象种类多,需要扩展性 ⭐⭐⭐ ✅ 是
抽象工厂模式 创建 多个相关对象 的工厂 需要管理多个产品族 ⭐⭐⭐⭐ ✅ 是

三、工厂模式的实现

(一)简单工厂模式(Simple Factory Pattern)

1. 介绍
  • 通过 一个工厂类 负责创建所有对象,根据 参数 返回不同的实例。
  • 缺点 :违反 开闭原则(OCP),每次新增对象类型都要修改工厂类。
2. 示例:支付系统(支付宝/微信支付)
python 复制代码
class Payment:
    def pay(self, amount):
        pass

class Alipay(Payment):
    def pay(self, amount):
        return f"使用支付宝支付 {amount} 元"

class WeChatPay(Payment):
    def pay(self, amount):
        return f"使用微信支付 {amount} 元"

class PaymentFactory:
    @staticmethod
    def create_payment(method):
        if method == "alipay":
            return Alipay()
        elif method == "wechat":
            return WeChatPay()
        else:
            raise ValueError("不支持的支付方式")

# 使用工厂创建对象
payment = PaymentFactory.create_payment("alipay")
print(payment.pay(100))  # 输出:使用支付宝支付 100 元
3. 优缺点

优点

  • 代码集中管理对象的创建,降低耦合度。
  • 适用于 对象种类少,变化不大的情况

缺点

  • 不符合开闭原则(OCP) ,新增支付方式需要修改 PaymentFactory 代码。

(二)工厂方法模式(Factory Method Pattern)

1. 介绍
  • 每个产品都有自己的工厂,创建逻辑封装在具体工厂类中。
  • 符合开闭原则(OCP),新增产品时无需修改现有代码,只需新增具体工厂类。
2. 示例:多种支付方式
python 复制代码
from abc import ABC, abstractmethod

# 抽象产品
class Payment(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

# 具体产品
class Alipay(Payment):
    def pay(self, amount):
        return f"使用支付宝支付 {amount} 元"

class WeChatPay(Payment):
    def pay(self, amount):
        return f"使用微信支付 {amount} 元"

# 抽象工厂
class PaymentFactory(ABC):
    @abstractmethod
    def create_payment(self):
        pass

# 具体工厂
class AlipayFactory(PaymentFactory):
    def create_payment(self):
        return Alipay()

class WeChatPayFactory(PaymentFactory):
    def create_payment(self):
        return WeChatPay()

# 使用工厂方法
factory = WeChatPayFactory()
payment = factory.create_payment()
print(payment.pay(200))  # 输出:使用微信支付 200 元
3. 优缺点

优点

  • 符合开闭原则,扩展新支付方式时,只需新增工厂类。
  • 每个产品的创建逻辑独立,符合 单一职责原则

缺点

  • 需要创建多个工厂类,代码量增加。

(三)抽象工厂模式(Abstract Factory Pattern)

1. 介绍
  • 工厂方法模式的扩展 ,用于创建 多个相关对象(产品族)
  • 适用于 多个产品族,如不同品牌的 UI 组件、数据库连接等。
2. 示例:支付 + 订单管理
python 复制代码
from abc import ABC, abstractmethod

# 抽象产品A:支付方式
class Payment(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

# 具体产品A
class Alipay(Payment):
    def pay(self, amount):
        return f"使用支付宝支付 {amount} 元"

class WeChatPay(Payment):
    def pay(self, amount):
        return f"使用微信支付 {amount} 元"

# 抽象产品B:订单管理
class OrderManager(ABC):
    @abstractmethod
    def create_order(self, order_id):
        pass

# 具体产品B
class AlipayOrderManager(OrderManager):
    def create_order(self, order_id):
        return f"支付宝创建订单 {order_id}"

class WeChatOrderManager(OrderManager):
    def create_order(self, order_id):
        return f"微信创建订单 {order_id}"

# 抽象工厂
class PaymentFactory(ABC):
    @abstractmethod
    def create_payment(self):
        pass

    @abstractmethod
    def create_order_manager(self):
        pass

# 具体工厂
class AlipayFactory(PaymentFactory):
    def create_payment(self):
        return Alipay()

    def create_order_manager(self):
        return AlipayOrderManager()

class WeChatFactory(PaymentFactory):
    def create_payment(self):
        return WeChatPay()

    def create_order_manager(self):
        return WeChatOrderManager()

# 使用抽象工厂
factory = WeChatFactory()
payment = factory.create_payment()
order_manager = factory.create_order_manager()

print(payment.pay(300))  # 输出:使用微信支付 300 元
print(order_manager.create_order("WX12345"))  # 输出:微信创建订单 WX12345
3. 优缺点

优点

  • 适用于 多个产品族,保证产品之间的兼容性。
  • 符合开闭原则,易于扩展。

缺点

  • 代码结构复杂,适用于大型系统。

四、总结与对比

设计模式 适用场景 是否符合开闭原则 是否易扩展 代码复杂度
简单工厂 对象种类少,变化不大 ❌ 否 ❌ 不易扩展 ⭐⭐
工厂方法 对象种类较多,需要扩展性 ✅ 是 ✅ 易扩展 ⭐⭐⭐
抽象工厂 需要创建多个相关对象(产品族) ✅ 是 ✅ 易扩展 ⭐⭐⭐⭐

五、如何选择合适的工厂模式?

  • 对象较少,创建逻辑简单简单工厂模式
  • 对象较多,扩展性要求高工厂方法模式
  • 需要创建多个相关对象(产品族)抽象工厂模式

通过 层层递进 的工厂模式,我们可以 封装对象创建逻辑 ,提高代码的 可维护性扩展性,在实际开发中选择合适的工厂模式,提升代码质量! 🚀

相关推荐
Antonio9151 小时前
【设计模式】状态模式
设计模式
木子庆五3 小时前
Android设计模式之工厂方法模式
android·设计模式·工厂方法模式
Absinthe_苦艾酒13 小时前
设计模式之适配器模式
设计模式·适配器模式
Zfox_16 小时前
【Linux】高性能网络模式:Reactor 反应堆模式
linux·服务器·c++·设计模式·性能优化·reactor
木子庆五18 小时前
Android 设计模式之适配器模式
android·设计模式·适配器模式
找了一圈尾巴1 天前
设计模式(创建型)-建造者模式
设计模式·建造者模式
HashFlag1 天前
Go常用的设计模式
开发语言·设计模式·golang
payload1 天前
创建型设计模式详解
设计模式
有龍则灵1 天前
装饰器设计模式在Dubbo中的应用—源码级解析
设计模式·dubbo
C4程序员1 天前
项目设计模式:责任链模式
设计模式·责任链模式