十个经典 Python 设计模式解析

2024年 5月 30日 69.2k 0

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

十个经典 Python 设计模式解析-1

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设计模式,掌握了它们,你的代码将会更有组织,更易于理解和维护。记住,编程不只是写代码,更是艺术创作!现在就去把这些模式运用到你的项目中,让它们大放异彩吧!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论