抽象工厂案例

wen java案例 2

本文目录导读:

抽象工厂案例

  1. 案例背景
  2. 抽象工厂核心结构
  3. 明亮风格产品族
  4. 暗黑风格产品族
  5. 未来风格产品族
  6. 具体工厂实现
  7. 客户端使用场景
  8. 演示代码
  9. 运行结果
  10. 模式优缺点分析
  11. 扩展建议

我将为您设计一个完整的抽象工厂模式案例,以跨平台UI组件库为场景,展示如何优雅地创建不同风格(暗黑/明亮)的UI组件。

案例背景

我们要开发一个UI框架,需要支持:

  • 明亮模式(Light):白色背景、深色文字
  • 暗黑模式(Dark):黑色背景、浅色文字
  • 未来模式(Future):霓虹风格

每个模式都需要提供按钮、输入框、对话框组件。

抽象工厂核心结构

from abc import ABC, abstractmethod
from typing import Dict, Type
# ---------- 抽象产品 ----------
class Button(ABC):
    @abstractmethod
    def render(self) -> str: ...
    @abstractmethod
    def click(self) -> str: ...
class Input(ABC):
    @abstractmethod
    def render(self) -> str: ...
    @abstractmethod
    def get_value(self) -> str: ...
class Dialog(ABC):
    @abstractmethod
    def render(self) -> str: ...
    @abstractmethod
    def show_message(self, message: str) -> str: ...
# ---------- 抽象工厂 ----------
class UIFactory(ABC):
    @abstractmethod
    def create_button(self) -> Button: ...
    @abstractmethod
    def create_input(self) -> Input: ...
    @abstractmethod
    def create_dialog(self) -> Dialog: ...

明亮风格产品族

# 明亮风格按钮
class LightButton(Button):
    def render(self):
        return "🔵 [明亮按钮] 白色背景+蓝色边框"
    def click(self):
        return "✨ 明亮按钮被点击!"
# 明亮风格输入框
class LightInput(Input):
    def render(self):
        return "🔲 [明亮输入框] 白底灰边"
    def get_value(self):
        return "这是明亮输入框的内容"
# 明亮风格对话框
class LightDialog(Dialog):
    def render(self):
        return "🪟 [明亮对话框] 白色弹窗+圆角阴影"
    def show_message(self, message):
        return f"💬 明亮对话框提示: {message}"

暗黑风格产品族

class DarkButton(Button):
    def render(self):
        return "🌑 [暗黑按钮] 深灰背景+紫色光效"
    def click(self):
        return "⚡ 暗黑按钮被点击!"
class DarkInput(Input):
    def render(self):
        return "🖤 [暗黑输入框] 黑色底+荧光绿边"
    def get_value(self):
        return "这是暗黑输入框的内容"
class DarkDialog(Dialog):
    def render(self):
        return "🌌 [暗黑对话框] 深色弹窗+霓虹边框"
    def show_message(self, message):
        return f"🗯️ 暗黑对话框提示: {message}"

未来风格产品族

class FutureButton(Button):
    def render(self):
        return "🚀 [未来按钮] 全息投影+动态流光"
    def click(self):
        return "🌀 未来按钮被点击,发出全息反馈!"
class FutureInput(Input):
    def render(self):
        return "👾 [未来输入框] 透明玻璃+蓝紫激光"
    def get_value(self):
        return "这是未来输入框的内容"
class FutureDialog(Dialog):
    def render(self):
        return "🕹️ [未来对话框] 3D全息弹窗+粒子特效"
    def show_message(self, message):
        return f"📡 未来对话框提示: {message}"

具体工厂实现

# 明亮模式工厂
class LightFactory(UIFactory):
    name = "明亮模式"
    def create_button(self) -> Button:
        return LightButton()
    def create_input(self) -> Input:
        return LightInput()
    def create_dialog(self) -> Dialog:
        return LightDialog()
# 暗黑模式工厂
class DarkFactory(UIFactory):
    name = "暗黑模式"
    def create_button(self) -> Button:
        return DarkButton()
    def create_input(self) -> Input:
        return DarkInput()
    def create_dialog(self) -> Dialog:
        return DarkDialog()
# 未来模式工厂
class FutureFactory(UIFactory):
    name = "未来模式"
    def create_button(self) -> Button:
        return FutureButton()
    def create_input(self) -> Input:
        return FutureInput()
    def create_dialog(self) -> Dialog:
        return FutureDialog()

客户端使用场景

class Application:
    """客户端使用的应用容器"""
    def __init__(self, factory: UIFactory):
        self.factory = factory
        self.button = factory.create_button()
        self.input = factory.create_input()
        self.dialog = factory.create_dialog()
    def display_ui(self):
        print(f"\n{'='*50}")
        print(f" 当前模式: {self.factory.name}")
        print('='*50)
        # 渲染各个组件
        print(" 组件展示:")
        print(f"  - {self.button.render()}")
        print(f"  - {self.input.render()}")
        print(f"  - {self.dialog.render()}")
        # 组件交互
        print("\n 组件交互:")
        print(f"  - {self.button.click()}")
        print(f"  - 输入框值: {self.input.get_value()}")
        print(f"  - {self.dialog.show_message('欢迎使用UI框架')}")
    def change_theme(self, new_factory: UIFactory):
        """动态切换主题(演示工厂替换)"""
        print(f"\n🔄 正在从 {self.factory.name} 切换到 {new_factory.name}...")
        self.factory = new_factory
        self.button = new_factory.create_button()
        self.input = new_factory.create_input()
        self.dialog = new_factory.create_dialog()

演示代码

def main():
    # 创建不同风格的UI
    print("🚀 抽象工厂模式 - 跨平台UI组件库演示")
    print("="*60)
    # 1. 明亮模式
    light_app = Application(LightFactory())
    light_app.display_ui()
    # 2. 暗黑模式
    dark_app = Application(DarkFactory())
    dark_app.display_ui()
    # 3. 未来模式
    future_app = Application(FutureFactory())
    future_app.display_ui()
    # 4. 动态切换主题
    print("\n" + "="*60)
    print(" 动态主题切换演示")
    print("="*60)
    app = Application(LightFactory())
    app.display_ui()
    app.change_theme(DarkFactory())
    app.display_ui()
    app.change_theme(FutureFactory())
    app.display_ui()
if __name__ == "__main__":
    main()

运行结果

🚀 抽象工厂模式 - 跨平台UI组件库演示
============================================================
==================================================
 当前模式: 明亮模式
==================================================
 组件展示:
  - 🔵 [明亮按钮] 白色背景+蓝色边框
  - 🔲 [明亮输入框] 白底灰边
  - 🪟 [明亮对话框] 白色弹窗+圆角阴影
 组件交互:
  - ✨ 明亮按钮被点击!
  - 输入框值: 这是明亮输入框的内容
  - 💬 明亮对话框提示: 欢迎使用UI框架
==================================================
 当前模式: 暗黑模式
==================================================
 组件展示:
  - 🌑 [暗黑按钮] 深灰背景+紫色光效
  - 🖤 [暗黑输入框] 黑色底+荧光绿边
  - 🌌 [暗黑对话框] 深色弹窗+霓虹边框
 组件交互:
  - ⚡ 暗黑按钮被点击!
  - 输入框值: 这是暗黑输入框的内容
  - 🗯️ 暗黑对话框提示: 欢迎使用UI框架
==================================================
 当前模式: 未来模式
==================================================
 组件展示:
  - 🚀 [未来按钮] 全息投影+动态流光
  - 👾 [未来输入框] 透明玻璃+蓝紫激光
  - 🕹️ [未来对话框] 3D全息弹窗+粒子特效
 组件交互:
  - 🌀 未来按钮被点击,发出全息反馈!
  - 输入框值: 这是未来输入框的内容
  - 📡 未来对话框提示: 欢迎使用UI框架
====================================================
 动态主题切换演示
====================================================
...(同上)

模式优缺点分析

✅ 优点

  1. 产品族一致性:确保同一主题的组件风格统一
  2. 开闭原则:添加新风格只需新增工厂和产品类
  3. 解耦:客户端只依赖抽象接口,不关心具体类

❌ 缺点

  1. 类数量爆炸:每个产品族都需要多个产品类
  2. 扩展困难:新增产品类型需要修改所有工厂
  3. 抽象限制:当需要创建非标准功能时灵活性受限

扩展建议

# 添加新风格只需:
class MinimalFactory(UIFactory):  # 极简风格
    name = "极简模式"
    def create_button(self): return MinimalButton()
    def create_input(self): return MinimalInput()
    def create_dialog(self): return MinimalDialog()
# 使用
app = Application(MinimalFactory())

这个案例完整展示了抽象工厂模式的核心理念——创建一组相关对象而不指定具体类,非常适合需要保证产品族兼容性的场景。

抱歉,评论功能暂时关闭!