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

选择建议

  • 从简单工厂 → 工厂方法 → 抽象工厂,灵活性递增 ,但复杂度也递增
  • 根据业务需求选择最简单能满足的模式。
相关推荐
阿闽ooo3 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4963 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃3 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20103 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈3 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||4 天前
安装依赖三方exe/msi的软件设计模式
设计模式
希望_睿智4 天前
实战设计模式之访问者模式
c++·设计模式·架构
茶本无香4 天前
设计模式之十六:状态模式(State Pattern)详解 -优雅地管理对象状态,告别繁琐的条件判断
java·设计模式·状态模式
驴儿响叮当20104 天前
设计模式之备忘录模式
设计模式·备忘录模式
驴儿响叮当20104 天前
设计模式之迭代器模式
设计模式·迭代器模式