大家好!今天咱們來聊聊Python編程中的那些“武林秘籍”——設計模式。它們就像編程界的暗號,讓你的代碼更加優雅、高效。讓我們一起揭開這些模式的神秘面紗,看看它們在實際項目中的神奇作用吧!
想象一下,你有個大冰箱,每次需要冰淇淋時,你都不用直接打開冷凍室,而是通過一個工廠方法來決定要哪種口味。
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()
好比給房間添加裝飾,改變外觀但不改變核心功能。比如,給打印語句加上顏色:
def color_decorator(func): def wrapper(color): print(f"{color} {func(color)}") return wrapper@color_decoratordef say_hello(name): print(f"Hello, {name}")say_hello("Python") # 輸出: Red Hello, Python
確保一個類只有一個實例,并提供全局訪問點。就像一個班級只有一個班長:
class Singleton: _instance = None def __new__(cls): if not cls._instance: cls._instance = super().__new__(cls) return cls._instanceclass MyClass(Singleton): passobj1 = MyClass()obj2 = MyClass() # obj1和obj2指向同一個實例
當數據變化時,所有依賴它的對象都會得到通知。就像天氣預報,一旦有新的天氣數據,所有訂閱者都會收到更新:
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: ...
在不同情況下使用不同的算法,而無需修改使用算法的代碼。就像烹飪,根據食材選擇不同的烹飪方式:
class CookingStrategy: def cook(self, ingredient): passclass 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...
讓不兼容的對象協同工作,就像老式電視和現代播放器之間的連接器:
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 ...
為對象提供一個替身,對原對象進行控制或包裝。想象一個網站緩存:
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()
遍歷集合而不需要暴露其內部結構。就像翻閱書頁:
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 resultbook = Book()for page in book: print(page) # 輸出: Page 1, Page 2, ..., Page 10
將請求封裝為對象,使你能夠推遲或更改請求的執行。就像點餐系統:
class Command: def execute(self): passclass 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 ...
通過共享對象來節約內存,減少重復。像打印海報,每個字母可以共享:
class Letter: def __init__(self, text): self.text = textclass 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個經典的Python設計模式,掌握了它們,你的代碼將會更有組織,更易于理解和維護。記住,編程不只是寫代碼,更是藝術創作!現在就去把這些模式運用到你的項目中,讓它們大放異彩吧!
本文鏈接:http://www.tebozhan.com/showinfo-26-91822-0.html十個經典 Python 設計模式解析
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com