10个经典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设计模式,掌握了它们,你的代码将会更有组织,更易于理解和维护。记住,编程不只是写代码,更是艺术创作!现在就去把这些模式运用到你的项目中,让它们大放异彩吧!
原文地址:https://blog.csdn.net/wenjie20070212/article/details/137670809
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!