十个经典 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

2023-12-01 18:06:35

2023-10-11 11:37:36

微服务架构

2024-04-11 09:13:17

设计模式开发

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数据查询

2024-04-28 10:00:24

Python数据可视化库图像处理库

2021-12-02 14:55:44

Python项目编程语言

2023-06-27 15:50:23

Python图像处理

2024-06-26 13:11:40

2023-12-22 15:44:43

2022-05-12 08:12:51

PythonPip技巧
点赞
收藏

51CTO技术栈公众号