以下是 Python 中常用設計模式 的分類總結與代碼示例,結合 Python 動態語言特性簡化實現,涵蓋創建型、結構型與行為型三大類:
一、創建型模式(Creational Patterns)
1. 單例模式(Singleton)
- 用途:確保類隻有一個實例(如配置管理、日誌記錄)。
- Pythonic 實現:
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls) return cls._instance # 使用 s1 = Singleton() s2 = Singleton() print(s1 is s2) # True
2. 工廠方法(Factory Method)
- 用途:解耦對象創建邏輯,允許子類決定實例化哪個類。
- 示例:
class Button: def render(self): pass class WindowsButton(Button): def render(self): return "Windows風格按鈕" class MacButton(Button): def render(self): return "Mac風格按鈕" class GUIFactory: def create_button(self): pass class WindowsFactory(GUIFactory): def create_button(self): return WindowsButton() class MacFactory(GUIFactory): def create_button(self): return MacButton() # 使用 factory = MacFactory() button = factory.create_button() print(button.render()) # Mac風格按鈕
3. 建造者模式(Builder)
- 用途:分步構建複雜對象(如生成複雜配置或文檔)。
- 鏈式調用實現:
class Pizza: def __init__(self): self.toppings = [] def add_topping(self, topping): self.toppings.append(topping) return self # 支持鏈式調用 # 使用 pizza = Pizza().add_topping("芝士").add_topping("火腿") print(pizza.toppings) # ['芝士', '火腿']
二、結構型模式(Structural Patterns)
1. 適配器模式(Adapter)
- 用途:轉換接口以兼容不同類(如舊係統整合)。
- 示例:
class OldSystem: def legacy_request(self): return "舊係統數據" class Adapter: def __init__(self, old_system): self.old_system = old_system def new_request(self): return f"適配後: {self.old_system.legacy_request()}" # 使用 adapter = Adapter(OldSystem()) print(adapter.new_request()) # 適配後: 舊係統數據
2. 裝飾器模式(Decorator)
- 用途:動態擴展對象功能(如日誌、緩存)。
- Python 裝飾器語法:
def log_decorator(func): def wrapper(*args, **kwargs): print(f"調用函數: {func.__name__}") return func(*args, **kwargs) return wrapper @log_decorator def say_hello(name): print(f"Hello, {name}!") say_hello("Alice") # 輸出:調用函數: say_hello → Hello, Alice!
3. 代理模式(Proxy)
- 用途:控製對象訪問(如延遲加載、權限檢查)。
- 示例:
class RealImage: def display(self): print("顯示高清圖片") class ProxyImage: def __init__(self): self._real_image = None def display(self): if self._real_image is None: self._real_image = RealImage() # 延遲加載 self._real_image.display() # 使用 proxy = ProxyImage() proxy.display() # 首次調用時加載並顯示
三、行為型模式(Behavioral Patterns)
1. 觀察者模式(Observer)
- 用途:實現對象間的事件通知(如消息訂閱)。
- Python 實現:
class Newsletter: def __init__(self): self._subscribers = [] def subscribe(self, subscriber): self._subscribers.append(subscriber) def notify(self, message): for sub in self._subscribers: sub.update(message) class Subscriber: def update(self, message): print(f"收到消息: {message}") # 使用 news = Newsletter() news.subscribe(Subscriber()) news.notify("新文章發布!") # 輸出:收到消息: 新文章發布!
2. 策略模式(Strategy)
- 用途:定義算法族並使其可互換(如排序策略切換)。
- 示例:
class PaymentStrategy: def pay(self, amount): pass class CreditCardPayment(PaymentStrategy): def pay(self, amount): print(f"信用卡支付 {amount} 元") class AlipayPayment(PaymentStrategy): def pay(self, amount): print(f"支付寶支付 {amount} 元") class PaymentContext: def __init__(self, strategy): self.strategy = strategy def execute_payment(self, amount): self.strategy.pay(amount) # 使用 context = PaymentContext(AlipayPayment()) context.execute_payment(100) # 支付寶支付 100 元
3. 狀態模式(State)
- 用途:根據對象狀態改變行為(如訂單狀態流轉)。
- 示例:
class OrderState: def next_state(self): pass class PendingState(OrderState): def next_state(self): print("訂單已確認 → 處理中") return ProcessingState() class ProcessingState(OrderState): def next_state(self): print("訂單處理完成 → 已發貨") return ShippedState() class Order: def __init__(self): self.state = PendingState() def advance(self): self.state = self.state.next_state() # 使用 order = Order() order.advance() # 訂單已確認 → 處理中 order.advance() # 訂單處理完成 → 已發貨
四、Python 特有簡化模式
1. 模塊單例
- 原理:利用 Python 模塊天然單例特性。
# config.py SETTINGS = {"debug": True} # main.py import config config.SETTINGS["debug"] = False # 全局唯一實例
2. 上下文管理器(Context Manager)
- 用途:資源自動管理(如文件、數據庫連接)。
class DatabaseConnection: def __enter__(self): print("連接數據庫") return self def __exit__(self, exc_type, exc_val, exc_tb): print("關閉連接") def query(self): print("執行查詢") # 使用 with DatabaseConnection() as db: db.query() # 輸出:連接數據庫 → 執行查詢 → 關閉連接
總結
- 優先使用Python特性:如裝飾器替代複雜模式,利用動態類型減少接口約束。
- 適用場景:
- Web框架:中間件(裝飾器)、路由(觀察者)。
- 數據處理:工廠生成不同解析器、策略模式切換算法。
- 異步編程:狀態模式管理協程狀態。
- 避免過度設計:Python強調簡潔,僅在複雜邏輯或擴展需求時引入模式。