【设计模式】1.简单工厂、工厂、抽象工厂模式

every blog every motto: You can do more than you think.
https://blog.csdn.net/weixin_39190382?type=blog

0. 前言

以下是 简单工厂模式工厂方法模式抽象工厂模式 的 Python 实现与对比,结合代码示例和实际应用场景说明:


1. 简单工厂模式(Simple Factory)

核心思想 :由一个工厂类根据传入的参数,动态决定创建哪一种产品类的实例。
适用场景:对象创建逻辑简单,且不需要频繁扩展新产品。

python 复制代码
from abc import ABC, abstractmethod

# 抽象产品
class Button(ABC):
    @abstractmethod
    def render(self):
        pass

# 具体产品
class WindowsButton(Button):
    def render(self):
        return "Windows 风格按钮"

class MacButton(Button):
    def render(self):
        return "Mac 风格按钮"

# 简单工厂
class ButtonFactory:
    @staticmethod
    def create_button(os_type: str) -> Button:
        if os_type == "windows":
            return WindowsButton()
        elif os_type == "mac":
            return MacButton()
        else:
            raise ValueError("未知操作系统类型")

# 使用
button = ButtonFactory.create_button("windows")
print(button.render())  # 输出: Windows 风格按钮

特点

  • 优点:客户端与具体产品解耦。
  • 缺点:违反开闭原则(新增产品需修改工厂类)。

2. 工厂方法模式(Factory Method)

核心思想 :将对象的创建延迟到子类,每个子类负责创建一种具体产品。
适用场景:需要支持多类产品的扩展,且创建逻辑较复杂。

python 复制代码
from abc import ABC, abstractmethod

# 抽象产品
class Button(ABC):
    @abstractmethod
    def render(self):
        pass

# 具体产品
class WindowsButton(Button):
    def render(self):
        return "Windows 按钮"

class MacButton(Button):
    def render(self):
        return "Mac 按钮"

# 抽象工厂
class Dialog(ABC):
    @abstractmethod
    def create_button(self) -> Button:
        pass

    def render(self):
        button = self.create_button()
        return f"渲染 {button.render()}"

# 具体工厂
class WindowsDialog(Dialog):
    def create_button(self) -> Button:
        return WindowsButton()

class MacDialog(Dialog):
    def create_button(self) -> Button:
        return MacButton()

# 使用
dialog = WindowsDialog()
print(dialog.render())  # 输出: "渲染 Windows 按钮"

特点

  • 优点:符合开闭原则(新增产品只需新增工厂子类)。
  • 缺点:类数量增多(每个产品对应一个工厂)。

3. 抽象工厂模式(Abstract Factory)

核心思想 :创建一组相关或依赖的对象(产品族),而不需指定具体类。
适用场景:需要创建多个系列的产品(如跨平台的 UI 组件)。

python 复制代码
from abc import ABC, abstractmethod

# 抽象产品族
class Button(ABC):
    @abstractmethod
    def render(self):
        pass

class Checkbox(ABC):
    @abstractmethod
    def render(self):
        pass

# Windows 产品族
class WindowsButton(Button):
    def render(self):
        return "Windows 按钮"

class WindowsCheckbox(Checkbox):
    def render(self):
        return "Windows 复选框"

# Mac 产品族
class MacButton(Button):
    def render(self):
        return "Mac 按钮"

class MacCheckbox(Checkbox):
    def render(self):
        return "Mac 复选框"

# 抽象工厂
class GUIFactory(ABC):
    @abstractmethod
    def create_button(self) -> Button:
        pass

    @abstractmethod
    def create_checkbox(self) -> Checkbox:
        pass

# 具体工厂
class WindowsFactory(GUIFactory):
    def create_button(self) -> Button:
        return WindowsButton()

    def create_checkbox(self) -> Checkbox:
        return WindowsCheckbox()

class MacFactory(GUIFactory):
    def create_button(self) -> Button:
        return MacButton()

    def create_checkbox(self) -> Checkbox:
        return MacCheckbox()

# 使用
def client_code(factory: GUIFactory):
    button = factory.create_button()
    checkbox = factory.create_checkbox()
    print(f"{button.render()} + {checkbox.render()}")

client_code(WindowsFactory())  # 输出: "Windows 按钮 + Windows 复选框"
client_code(MacFactory())      # 输出: "Mac 按钮 + Mac 复选框"

特点

  • 优点:支持产品族的扩展,保证兼容性。
  • 缺点:代码复杂度高,新增产品族需修改抽象工厂接口。

4. 三种模式对比总结

模式 核心区别 适用场景
简单工厂 一个工厂类创建所有产品 产品类型固定,无需扩展
工厂方法 每个产品对应一个工厂子类 需要支持单一产品的多维度扩展
抽象工厂 一个工厂创建一组相关产品(产品族) 需要保证多个产品的兼容性(如 UI)

选择建议

  • 从简单工厂 → 工厂方法 → 抽象工厂,灵活性递增 ,但复杂度也递增
  • 根据业务需求选择最简单能满足的模式。
相关推荐
杨充13 小时前
10.可测试性实战设计
设计模式·开源·代码规范
杨充13 小时前
9.重构十二式的实战
设计模式·开源·代码规范
杨充13 小时前
6.设计原则的全景图
设计模式·开源·全栈
杨充13 小时前
2.面向对象的特性
设计模式
杨充13 小时前
7.SOLID原则案例汇
设计模式·开源·全栈
杨充13 小时前
8.反模式与坏味道
设计模式·开源·代码规范
杨充13 小时前
3.接口vs抽象类比较
设计模式
咖啡八杯16 小时前
文法、BNF与AST
java·设计模式·解释器模式·ast·文法
咖啡八杯1 天前
GoF设计模式——解释器模式
java·后端·spring·设计模式