当前位置:首页 > 科技  > 软件

十个经典 Python 设计模式解析

来源: 责编: 时间:2024-05-30 17:16:27 268观看
导读大家好!今天咱们来聊聊Python编程中的那些“武林秘籍”——设计模式。它们就像编程界的暗号,让你的代码更加优雅、高效。让我们一起揭开这些模式的神秘面纱,看看它们在实际项目中的神奇作用吧!1. 工厂模式(Factory Pattern

大家好!今天咱们来聊聊Python编程中的那些“武林秘籍”——设计模式。它们就像编程界的暗号,让你的代码更加优雅、高效。让我们一起揭开这些模式的神秘面纱,看看它们在实际项目中的神奇作用吧!Asr28资讯网——每日最新资讯28at.com

Asr28资讯网——每日最新资讯28at.com

1. 工厂模式(Factory Pattern)

想象一下,你有个大冰箱,每次需要冰淇淋时,你都不用直接打开冷冻室,而是通过一个工厂方法来决定要哪种口味。Asr28资讯网——每日最新资讯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)

好比给房间添加装饰,改变外观但不改变核心功能。比如,给打印语句加上颜色:Asr28资讯网——每日最新资讯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)

确保一个类只有一个实例,并提供全局访问点。就像一个班级只有一个班长:Asr28资讯网——每日最新资讯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)

当数据变化时,所有依赖它的对象都会得到通知。就像天气预报,一旦有新的天气数据,所有订阅者都会收到更新:Asr28资讯网——每日最新资讯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)

在不同情况下使用不同的算法,而无需修改使用算法的代码。就像烹饪,根据食材选择不同的烹饪方式:Asr28资讯网——每日最新资讯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)

让不兼容的对象协同工作,就像老式电视和现代播放器之间的连接器:Asr28资讯网——每日最新资讯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)

为对象提供一个替身,对原对象进行控制或包装。想象一个网站缓存:Asr28资讯网——每日最新资讯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)

遍历集合而不需要暴露其内部结构。就像翻阅书页:Asr28资讯网——每日最新资讯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)

将请求封装为对象,使你能够推迟或更改请求的执行。就像点餐系统:Asr28资讯网——每日最新资讯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)

通过共享对象来节约内存,减少重复。像打印海报,每个字母可以共享:Asr28资讯网——每日最新资讯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设计模式,掌握了它们,你的代码将会更有组织,更易于理解和维护。记住,编程不只是写代码,更是艺术创作!现在就去把这些模式运用到你的项目中,让它们大放异彩吧!Asr28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-91822-0.html十个经典 Python 设计模式解析

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。邮件:2376512515@qq.com

上一篇: 用于时间序列中的变点检测算法,你学会了吗?

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

标签:
  • 热门焦点
  • 一加Ace2 Pro真机揭晓 钛空灰配色质感拉满

    终于,在经过了几波预热之后,一加Ace2 Pro的外观真机图在网上出现了。还是博主数码闲聊站曝光的,这次的外观设计还是延续了一加11的方案,只是细节上有了调整,例如新加入了钛空灰
  • 中兴AX5400Pro+上手体验:再升级 双2.5G网口+USB 3.0这次全都有

    2021年11月的时候,中兴先后发布了两款路由器产品,中兴AX5400和中兴AX5400 Pro,从产品命名上就不难看出这是隶属于同一系列的,但在外观设计上这两款产品可以说是完全没一点关系
  • 石头自清洁扫拖机器人G10S评测:多年黑科技集大成之作 懒人终极福音

    科技圈经常能看到一个词叫“缝合怪”,用来形容那些把好多功能或者外观结合在一起的产品,通常这样的词是贬义词,但如果真的是产品缝合的好、缝合的实用的话,那它就成了中性词,今
  • 5月iOS设备好评榜:iPhone 14仅排第43?

    来到新的一月,安兔兔的各个榜单又重新汇总了数据,像安卓阵营的榜单都有着比较大的变动,不过iOS由于设备的更新换代并没有那么快,所以相对来说变化并不大,特别是iOS好评榜,老款设
  • JavaScript 混淆及反混淆代码工具

    介绍在我们开始学习反混淆之前,我们首先要了解一下代码混淆。如果不了解代码是如何混淆的,我们可能无法成功对代码进行反混淆,尤其是使用自定义混淆器对其进行混淆时。什么是混
  • 学习JavaScript的10个理由...

    作者 | Simplilearn编译 | 王瑞平当你决心学习一门语言的时候,很难选择到底应该学习哪一门,常用的语言有Python、Java、JavaScript、C/CPP、PHP、Swift、C#、Ruby、Objective-
  • 共享单车的故事讲到哪了?

    来源丨海克财经与共享充电宝相差不多,共享单车已很久没有被国内热点新闻关照到了。除了一再涨价和用户直呼用不起了。近日多家媒体再发报道称,成都、天津、郑州等地多个共享单
  • 腾讯VS网易,最卷游戏暑期档,谁能笑到最后?

    作者:无锈钵来源:财经无忌7月16日晚,上海1862时尚艺术中心。伴随着幻象的精准命中,硕大的荧幕之上,比分被定格在了14:12,被寄予厚望的EDG战队以绝对的优势战胜了BLG战队,拿下了总决
  • AI艺术欣赏体验会在上海梅赛德斯奔驰中心音乐俱乐部上演

    光影交错的镜像世界,虚实幻化的视觉奇观,虚拟偶像与真人共同主持,这些场景都出现在2019世界人工智能大会的舞台上。8月29日至31日,“AI艺术欣赏体验会”在上海
Top