成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

十個經典 Python 設計模式解析

開發 前端
本文將介紹十個經典的 Python 設計模式,掌握了它們,你的代碼將會更有組織,更易于理解和維護。

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

1. 工廠模式(Factory Pattern)

想象一下,你有個大冰箱,每次需要冰淇淋時,你都不用直接打開冷凍室,而是通過一個工廠方法來決定要哪種口味。

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)

好比給房間添加裝飾,改變外觀但不改變核心功能。比如,給打印語句加上顏色:

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)

確保一個類只有一個實例,并提供全局訪問點。就像一個班級只有一個班長:

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

4. 觀察者模式(Observer Pattern)

當數據變化時,所有依賴它的對象都會得到通知。就像天氣預報,一旦有新的天氣數據,所有訂閱者都會收到更新:

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)

在不同情況下使用不同的算法,而無需修改使用算法的代碼。就像烹飪,根據食材選擇不同的烹飪方式:

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)

讓不兼容的對象協同工作,就像老式電視和現代播放器之間的連接器:

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)

為對象提供一個替身,對原對象進行控制或包裝。想象一個網站緩存:

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)

遍歷集合而不需要暴露其內部結構。就像翻閱書頁:

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)

將請求封裝為對象,使你能夠推遲或更改請求的執行。就像點餐系統:

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)

通過共享對象來節約內存,減少重復。像打印海報,每個字母可以共享:

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

責任編輯:趙寧寧 來源: 手把手PythonAI編程
相關推薦

2024-08-26 14:57:36

2024-04-07 08:12:54

設計模式工具

2010-09-08 14:35:22

CSS

2024-11-11 07:00:00

Python圖像識別

2022-09-05 08:34:48

設計模式微服務Web

2024-07-18 15:08:27

2024-12-31 08:10:00

2023-10-11 11:37:36

微服務架構

2023-12-01 18:06:35

2024-04-11 09:13:17

設計模式開發

2024-12-03 14:33:42

Python遞歸編程

2024-01-30 00:40:10

2010-09-03 14:57:33

CSS樣式表CSS

2012-11-23 10:30:28

Responsive響應式Web

2023-12-04 14:28:15

模型應用設計

2022-08-26 09:38:39

Pandas數據查詢

2021-12-02 14:55:44

Python項目編程語言

2024-04-28 10:00:24

Python數據可視化庫圖像處理庫

2023-06-27 15:50:23

Python圖像處理

2024-09-23 00:00:00

下拉菜單UI控件
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 黄色毛片一级 | 亚洲欧美bt | 毛片毛片毛片毛片 | 久久久久国产一级毛片高清网站 | 精品成人佐山爱一区二区 | 中文字幕一区二区三区精彩视频 | 日韩一级精品视频在线观看 | 国产精品久久久久久久久免费相片 | 一级特黄a大片 | 国产丝袜一区二区三区免费视频 | 国产美女精品 | 欧美一级网站 | 精品久久久999 | 青青草视频网站 | 中文字幕在线观看 | 羞羞色网站 | 久久久久国产一级毛片 | 国产美女精品 | 在线播放国产一区二区三区 | 国产精品69久久久久水密桃 | 亚洲视频中文字幕 | 久久国产综合 | 日本午夜一区 | 久久机热 | 亚洲国产精久久久久久久 | 色综合久久久久 | 九色 在线| 九九热国产精品视频 | 在线免费观看黄色网址 | 国产精品久久久久久一级毛片 | 久久久久免费精品国产小说色大师 | 91精品久久久 | 精品久久久网站 | 免费a大片 | 日韩欧美在线视频 | 久草www| 超碰在线97国产 | 午夜视频免费在线观看 | 欧美精品久久久久久久久久 | 精品中文字幕一区二区 | 日韩在线观看视频一区 |