【设计模式】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)

选择建议

  • 从简单工厂 → 工厂方法 → 抽象工厂,灵活性递增 ,但复杂度也递增
  • 根据业务需求选择最简单能满足的模式。
相关推荐
一块plus32 分钟前
2025 年值得一玩的最佳 Web3 游戏
算法·设计模式·程序员
缘来是庄1 小时前
设计模式之代理模式
java·设计模式·代理模式
勤奋的知更鸟2 小时前
Java 编程之策略模式详解
java·设计模式·策略模式
暮乘白帝过重山2 小时前
设计模式篇:灵活多变的策略模式
设计模式·策略模式
GodKeyNet3 小时前
设计模式-策略模式
设计模式·策略模式
DKPT4 小时前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄4 小时前
设计模式之外观模式
java·设计模式·外观模式
你是橙子那我是谁4 小时前
设计模式之外观模式:简化复杂系统的优雅之道
设计模式
哈里谢顿5 小时前
python 设计模式
设计模式
OpenC++5 小时前
【C++】备忘录模式
c++·设计模式·备忘录模式