design_pattern
Design Pattern
監聽者模式
在物件間定義一種一對多的依賴關係,當這個物件狀態發生改變時,所有依賴他的物件都會被通知並自動更新
Python 範例
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self, msg):
for observer in self._observers:
observer.update(msg)
class Observer:
def update(self, msg):
print(f"Received: {msg}")
subject = Subject()
observer1 = Observer()
observer2 = Observer()
subject.attach(observer1)
subject.attach(observer2)
subject.notify("Hello Observers!")
# Output:
# Received: Hello Observers!
# Received: Hello Observers!
這種模式常用於事件系統、GUI 框架、資料同步等場景。
裝飾者模式
動態地給物件增加職責,就像包裝一層一層的裝飾品一樣,不需改變原本的類別。
Python 範例
class Coffee:
def cost(self):
return 5
class MilkDecorator:
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost() + 2
class SugarDecorator:
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost() + 1
coffee = Coffee()
print(coffee.cost()) # 5
coffee = MilkDecorator(coffee)
print(coffee.cost()) # 7
coffee = SugarDecorator(coffee)
print(coffee.cost()) # 8
裝飾者模式常用於需要動態擴充功能、避免類別爆炸的場景,例如 I/O stream、middleware 等。
Python 語言層級的裝飾器
Python 本身支援函式/方法的裝飾器(decorator),可用來動態擴充函式功能,語法簡潔,常見於日誌、權限驗證、快取等場景。
def my_decorator(func):
def wrapper(*args, **kwargs):
print("執行前...")
result = func(*args, **kwargs)
print("執行後...")
return result
return wrapper
@my_decorator
def say_hello(name):
print(f"Hello, {name}")
say_hello("Jimmy")
# Output:
# 執行前...
# Hello, Jimmy
# 執行後...
Python 的 @decorator 語法糖讓裝飾器應用更直觀,能有效分離橫切關注點(如日誌、驗證、計時等)。
單例模式 (Singleton)
確保一個類別只有一個實例,並提供全域存取點。
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a = Singleton()
b = Singleton()
print(a is b) # True
工廠模式 (Factory)
定義一個用於建立物件的介面,讓子類決定實例化哪個類別。
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def animal_factory(kind):
if kind == "dog":
return Dog()
elif kind == "cat":
return Cat()
pet = animal_factory("dog")
print(pet.speak()) # Woof!