AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

十個經典 Python 設計模式解析

來源: 責編: 時間:2024-05-30 17:16:27 153觀看
導讀大家好!今天咱們來聊聊Python編程中的那些“武林秘籍”——設計模式。它們就像編程界的暗號,讓你的代碼更加優雅、高效。讓我們一起揭開這些模式的神秘面紗,看看它們在實際項目中的神奇作用吧!1. 工廠模式(Factory Pattern

大家好!今天咱們來聊聊Python編程中的那些“武林秘籍”——設計模式。它們就像編程界的暗號,讓你的代碼更加優雅、高效。讓我們一起揭開這些模式的神秘面紗,看看它們在實際項目中的神奇作用吧!LJP28資訊網——每日最新資訊28at.com

LJP28資訊網——每日最新資訊28at.com

1. 工廠模式(Factory Pattern)

想象一下,你有個大冰箱,每次需要冰淇淋時,你都不用直接打開冷凍室,而是通過一個工廠方法來決定要哪種口味。LJP28資訊網——每日最新資訊28at.com

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)

好比給房間添加裝飾,改變外觀但不改變核心功能。比如,給打印語句加上顏色:LJP28資訊網——每日最新資訊28at.com

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

3. 單例模式(Singleton Pattern)

確保一個類只有一個實例,并提供全局訪問點。就像一個班級只有一個班長:LJP28資訊網——每日最新資訊28at.com

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指向同一個實例

4. 觀察者模式(Observer Pattern)

當數據變化時,所有依賴它的對象都會得到通知。就像天氣預報,一旦有新的天氣數據,所有訂閱者都會收到更新:LJP28資訊網——每日最新資訊28at.com

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)

在不同情況下使用不同的算法,而無需修改使用算法的代碼。就像烹飪,根據食材選擇不同的烹飪方式:LJP28資訊網——每日最新資訊28at.com

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...

6. 適配器模式(Adapter Pattern)

讓不兼容的對象協同工作,就像老式電視和現代播放器之間的連接器:LJP28資訊網——每日最新資訊28at.com

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)

為對象提供一個替身,對原對象進行控制或包裝。想象一個網站緩存:LJP28資訊網——每日最新資訊28at.com

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)

遍歷集合而不需要暴露其內部結構。就像翻閱書頁:LJP28資訊網——每日最新資訊28at.com

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

9. 命令模式(Command Pattern)

將請求封裝為對象,使你能夠推遲或更改請求的執行。就像點餐系統:LJP28資訊網——每日最新資訊28at.com

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 ...

10. 享元模式(Flyweight Pattern)

通過共享對象來節約內存,減少重復。像打印海報,每個字母可以共享:LJP28資訊網——每日最新資訊28at.com

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設計模式,掌握了它們,你的代碼將會更有組織,更易于理解和維護。記住,編程不只是寫代碼,更是藝術創作!現在就去把這些模式運用到你的項目中,讓它們大放異彩吧!LJP28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-91822-0.html十個經典 Python 設計模式解析

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 用于時間序列中的變點檢測算法,你學會了嗎?

下一篇: C# 中的 Action 和 Func 委托

標簽:
  • 熱門焦點
Top