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

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

十個經典 Python 設計模式解析

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

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

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

1. 工廠模式(Factory Pattern)

想象一下,你有個大冰箱,每次需要冰淇淋時,你都不用直接打開冷凍室,而是通過一個工廠方法來決定要哪種口味。nYa28資訊網——每日最新資訊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)

好比給房間添加裝飾,改變外觀但不改變核心功能。比如,給打印語句加上顏色:nYa28資訊網——每日最新資訊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)

確保一個類只有一個實例,并提供全局訪問點。就像一個班級只有一個班長:nYa28資訊網——每日最新資訊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)

當數據變化時,所有依賴它的對象都會得到通知。就像天氣預報,一旦有新的天氣數據,所有訂閱者都會收到更新:nYa28資訊網——每日最新資訊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)

在不同情況下使用不同的算法,而無需修改使用算法的代碼。就像烹飪,根據食材選擇不同的烹飪方式:nYa28資訊網——每日最新資訊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)

讓不兼容的對象協同工作,就像老式電視和現代播放器之間的連接器:nYa28資訊網——每日最新資訊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)

為對象提供一個替身,對原對象進行控制或包裝。想象一個網站緩存:nYa28資訊網——每日最新資訊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)

遍歷集合而不需要暴露其內部結構。就像翻閱書頁:nYa28資訊網——每日最新資訊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)

將請求封裝為對象,使你能夠推遲或更改請求的執行。就像點餐系統:nYa28資訊網——每日最新資訊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)

通過共享對象來節約內存,減少重復。像打印海報,每個字母可以共享:nYa28資訊網——每日最新資訊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設計模式,掌握了它們,你的代碼將會更有組織,更易于理解和維護。記住,編程不只是寫代碼,更是藝術創作!現在就去把這些模式運用到你的項目中,讓它們大放異彩吧!nYa28資訊網——每日最新資訊28at.com

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

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

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

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

標簽:
  • 熱門焦點
  • 對標蘋果的靈動島 華為帶來實況窗功能

    繼蘋果的靈動島之后,華為也在今天正式推出了“實況窗”功能。據今天鴻蒙OS 4.0的現場演示顯示,華為的實況窗可以更高效的展現出實時通知,比如鎖屏上就能看到外賣、打車、銀行
  • K8S | Service服務發現

    一、背景在微服務架構中,這里以開發環境「Dev」為基礎來描述,在K8S集群中通常會開放:路由網關、注冊中心、配置中心等相關服務,可以被集群外部訪問;圖片對于測試「Tes」環境或者
  • 企業采用CRM系統的11個好處

    客戶關系管理(CRM)軟件可以為企業提供很多的好處,從客戶保留到提高生產力。  CRM軟件用于企業收集客戶互動,以改善客戶體驗和滿意度。  CRM軟件市場規模如今超過580
  • JavaScript學習 -AES加密算法

    引言在當今數字化時代,前端應用程序扮演著重要角色,用戶的敏感數據經常在前端進行加密和解密操作。然而,這樣的操作在網絡傳輸和存儲中可能會受到惡意攻擊的威脅。為了確保數據
  • 花7萬退貨退款無門:誰在縱容淘寶珠寶商家造假?

    來源:極點商業作者:楊銘在淘寶購買珠寶玉石后,因為保證金不夠賠付,店鋪關閉,退貨退款難、維權無門的比比皆是。“提供相關產品鑒定證書,支持全國復檢,可以30天無理由退換貨。&
  • 品牌洞察丨服務本地,美團直播成效幾何?

    來源:17PR7月11日,美團App首頁推薦位出現“美團直播”的固定入口。在直播聚合頁面,外賣“神槍手”直播間、美團旅行直播間、美團買菜直播間等均已上線,同時
  • 半導體需求下滑 三星電子DS業務部門今年營業虧損預計超10萬億韓元

    7月17日消息,據外媒報道,去年下半年開始的半導體需求下滑,影響到了三星電子、SK海力士、英特爾等諸多廠商,營收明顯下滑,部分廠商甚至出現了虧損。作為
  • 質感不錯!OPPO K11渲染圖曝光:旗艦IMX890傳感器首次下放

    一直以來,OPPO K系列機型都保持著較為均衡的產品體驗,歷來都是2K價位的明星機型,去年推出的OPPO K10和OPPO K10 Pro兩款機型憑借各自的出色配置,堪稱有
  • 朋友圈可以修改可見范圍了 蘋果用戶可率先體驗

    近日,iOS用戶迎來微信8.0.27正式版更新,除了可更換二維碼背景外,還新增了多項實用功能。在新版微信中,朋友圈終于可以修改可見范圍,簡單來說就是已發布的朋友圈
Top