十個(gè)經(jīng)典 Python 設(shè)計(jì)模式解析
大家好!今天咱們來(lái)聊聊Python編程中的那些“武林秘籍”——設(shè)計(jì)模式。它們就像編程界的暗號(hào),讓你的代碼更加優(yōu)雅、高效。讓我們一起揭開(kāi)這些模式的神秘面紗,看看它們?cè)趯?shí)際項(xiàng)目中的神奇作用吧!
1. 工廠模式(Factory Pattern)
想象一下,你有個(gè)大冰箱,每次需要冰淇淋時(shí),你都不用直接打開(kāi)冷凍室,而是通過(guò)一個(gè)工廠方法來(lái)決定要哪種口味。
def create_creamy_icecream(): return CreamyIceCream()
def create_fruit_icecream(): return FruitIceCream()
class IceCreamFactory:
@staticmethod
def get_icecream(kind):
if kind == 'creamy':
return create_creamy_icecream()
elif kind == 'fruit':
return create_fruit_icecream()
2. 裝飾器模式(Decorator Pattern)
好比給房間添加裝飾,改變外觀但不改變核心功能。比如,給打印語(yǔ)句加上顏色:
def color_decorator(func):
def wrapper(color):
print(f"{color} {func(color)}")
return wrapper
@color_decorator
def say_hello(name): print(f"Hello, {name}")
say_hello("Python") # 輸出: Red Hello, Python
3. 單例模式(Singleton Pattern)
確保一個(gè)類只有一個(gè)實(shí)例,并提供全局訪問(wèn)點(diǎn)。就像一個(gè)班級(jí)只有一個(gè)班長(zhǎng):
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
class MyClass(Singleton):
pass
obj1 = MyClass()
obj2 = MyClass() # obj1和obj2指向同一個(gè)實(shí)例
4. 觀察者模式(Observer Pattern)
當(dāng)數(shù)據(jù)變化時(shí),所有依賴它的對(duì)象都會(huì)得到通知。就像天氣預(yù)報(bào),一旦有新的天氣數(shù)據(jù),所有訂閱者都會(huì)收到更新:
class Subject:
def attach(self, observer): self.observers.append(observer)
def detach(self, observer): self.observers.remove(observer)
def notify(self): for observer in self.observers: observer.update()
class Observer:
def update(self, data): print(f"New data: {data}")
subject = Subject()
observer1 = Observer()
subject.attach(observer1)
subject.notify() # 輸出: New data: ...
5. 策略模式(Strategy Pattern)
在不同情況下使用不同的算法,而無(wú)需修改使用算法的代碼。就像烹飪,根據(jù)食材選擇不同的烹飪方式:
class CookingStrategy:
def cook(self, ingredient): pass
class BoilingStrategy(CookingStrategy):
def cook(self, ingredient): print(f"Heating {ingredient} to boil...")
class GrillingStrategy(CookingStrategy):
def cook(self, ingredient): print(f"Grilling {ingredient}...")
class Kitchen:
def __init__(self, strategy):
self.strategy = strategy
def cook(self, ingredient):
self.strategy.cook(ingredient)
kitchen = Kitchen(BoilingStrategy())
kitchen.cook("water") # 輸出: Heating water to boil...
6. 適配器模式(Adapter Pattern)
讓不兼容的對(duì)象協(xié)同工作,就像老式電視和現(xiàn)代播放器之間的連接器:
class OldTV:
def play(self, channel): print(f"Watching channel {channel}")
class RemoteAdapter:
def __init__(self, tv):
self.tv = tv
def press_button(self, command): getattr(self.tv, command)()
remote = RemoteAdapter(OldTV())
remote.press_button("play") # 輸出: Watching channel ...
7. 代理模式(Proxy Pattern)
為對(duì)象提供一個(gè)替身,對(duì)原對(duì)象進(jìn)行控制或包裝。想象一個(gè)網(wǎng)站緩存:
class RemoteImage:
def __init__(self, url):
self.url = url
def display(self):
print(f"Displaying image from {self.url}")
class LocalImageProxy(RemoteImage):
def display(self):
print("Loading image from cache...")
super().display()
8. 迭代器模式(Iterator Pattern)
遍歷集合而不需要暴露其內(nèi)部結(jié)構(gòu)。就像翻閱書(shū)頁(yè):
class Book:
def __iter__(self):
self.page = 1
return self
def __next__(self):
if self.page > 10:
raise StopIteration
result = f"Page {self.page}"
self.page += 1
return result
book = Book()
for page in book: print(page) # 輸出: Page 1, Page 2, ..., Page 10
9. 命令模式(Command Pattern)
將請(qǐng)求封裝為對(duì)象,使你能夠推遲或更改請(qǐng)求的執(zhí)行。就像點(diǎn)餐系統(tǒng):
class Command:
def execute(self): pass
class Order(Command):
def execute(self, item): print(f"Preparing {item}...")
class Kitchen:
def execute_order(self, cmd): cmd.execute()
order = Order()
kitchen = Kitchen()
kitchen.execute_order(order) # 輸出: Preparing ...
10. 享元模式(Flyweight Pattern)
通過(guò)共享對(duì)象來(lái)節(jié)約內(nèi)存,減少重復(fù)。像打印海報(bào),每個(gè)字母可以共享:
class Letter:
def __init__(self, text):
self.text = text
class FlyweightLetter(Letter):
_instances = {}
def __new__(cls, text):
if text not in cls._instances:
cls._instances[text] = super().__new__(cls, text)
return cls._instances[text]
poster = "Python"
print([l.text for l in poster]) # 輸出: ['P', 'y', 't', 'h', 'o', 'n']
以上就是10個(gè)經(jīng)典的Python設(shè)計(jì)模式,掌握了它們,你的代碼將會(huì)更有組織,更易于理解和維護(hù)。記住,編程不只是寫(xiě)代碼,更是藝術(shù)創(chuàng)作!現(xiàn)在就去把這些模式運(yùn)用到你的項(xiàng)目中,讓它們大放異彩吧!