很好!你现在已经开始接触设计模式了,而**抽象工厂模式(Abstract Factory Pattern)是一种常用于“创建一系列相关产品”**的经典设计模式。
我会一步步帮你理解:
抽象工厂模式:提供一个接口,用于创建一系列相关或相互依赖的对象,而无需指定它们的具体类。
当你面对以下场景时,它就很有用:
“我有多个产品(按钮、窗口、菜单),而且这些产品有不同的风格(比如 Mac 风格、Windows 风格),希望能在不改代码的前提下切换整套产品风格。”
你要布置房间,选一整套家具。你不能桌子 IKEA 风、椅子中式风格,应该风格统一。
→ 你只选工厂,不关心家具内部怎么造。
from abc import ABC, abstractmethod
class Button(ABC):
@abstractmethod
def click(self):
pass
class Window(ABC):
@abstractmethod
def open(self):
pass
class MacButton(Button):
def click(self):
print("Mac Button clicked!")
class WinButton(Button):
def click(self):
print("Windows Button clicked!")
class MacWindow(Window):
def open(self):
print("Mac Window opened!")
class WinWindow(Window):
def open(self):
print("Windows Window opened!")
class GUIFactory(ABC):
@abstractmethod
def create_button(self) -> Button:
pass
@abstractmethod
def create_window(self) -> Window:
pass
class MacFactory(GUIFactory):
def create_button(self):
return MacButton()
def create_window(self):
return MacWindow()
class WinFactory(GUIFactory):
def create_button(self):
return WinButton()
def create_window(self):
return WinWindow()
def render_ui(factory: GUIFactory):
button = factory.create_button()
window = factory.create_window()
button.click()
window.open()
# 使用 Mac 风格
render_ui(MacFactory())
# 使用 Windows 风格
render_ui(WinFactory())
✅ 抽象工厂负责生产“产品系列”,只换工厂,不动逻辑。适用于“同一风格的多组件系统”。
如果你希望,我可以把这个例子替换成游戏皮肤工厂、汽车工厂、手机UI工厂来帮助你更贴近生活。你想试试哪个?