设计模式是软件开发中的原则,它们提供了解决特定问题的通用解决方案。在 Python 中,由于其动态语言特性,设计模式不仅易于实现,还可以根据具体需求进行灵活调整。本篇文章将从传统的 创建型模式、结构型模式 和 行为型模式 出发,结合 Python 独有的动态特性,全面剖析最常用的设计模式。
目录
1. 责任链模式(Chain of Responsibility)
一、创建型模式
创建型模式主要用于控制对象的创建过程,避免直接实例化对象,从而提高代码的灵活性和可维护性。
1. 单例模式(Singleton)
定义:确保一个类只有一个实例,并提供全局访问点。
应用场景:
- 配置管理类
- 数据库连接池
实现示例:
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
# 测试单例
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # 输出:True
2. 工厂方法模式(Factory Method)
定义:定义一个接口,让子类决定实例化哪一个类。
应用场景:
- 动态对象生成
- 日志记录器
实现示例:
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
class AnimalFactory:
@staticmethod
def get_animal(animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
else:
raise ValueError("Unknown animal type")
# 测试工厂方法
animal = AnimalFactory.get_animal("dog")
print(animal.speak()) # 输出:Woof!
3. 抽象工厂模式(Abstract Factory)
定义:提供一个接口,创建一组相关或依赖的对象,而无需指定具体类。
应用场景:
- 跨平台系统组件
- 数据格式适配
实现示例:
class WindowsButton:
def render(self):
print("Windows Button")
class MacOSButton:
def render(self):
print("MacOS Button")
class GUIFactory:
@staticmethod
def get_factory(os_type):
if os_type == "Windows":
return WindowsButton()
elif os_type == "MacOS":
return MacOSButton()
else:
raise ValueError("Unknown OS type")
# 测试抽象工厂
button = GUIFactory.get_factory("Windows")
button.render() # 输出:Windows Button
4. 建造者模式(Builder)
定义:分步骤构建复杂对象,将创建过程与表示分离。
应用场景:
- 构建复杂对象,如报告生成器
实现示例:
class Report:
def __init__(self):
self.title = None
self.content = None
def show(self):
print(f"Title: {self.title}\nContent: {self.content}")
class ReportBuilder:
def __init__(self):
self.report = Report()
def set_title(self, title):
self.report.title = title
def set_content(self, content):
self.report.content = content
def build(self):
return self.report
# 测试建造者模式
builder = ReportBuilder()
builder.set_title("Monthly Report")
builder.set_content("This is the content of the report.")
report = builder.build()
report.show()
5. 原型模式(Prototype)
定义:通过复制现有实例创建新对象,而不是直接实例化。
应用场景:
- 大量相似对象的快速创建
实现示例:
import copy
class Prototype:
def __init__(self, name, attributes):
self.name = name
self.attributes = attributes
def clone(self):
return copy.deepcopy(self)
# 测试原型模式
prototype = Prototype("Prototype1", {"key": "value"})
clone = prototype.clone()
print(clone.name, clone.attributes) # 输出:Prototype1 {'key': 'value'}
二、结构型模式
结构型模式关注对象间的组合,通过更大的结构来扩展功能。
1. 适配器模式(Adapter)
定义:将一个类的接口转换为另一个类可以使用的接口。
应用场景:
- 解决接口不兼容问题
实现示例:
class OldSystem:
def old_method(self):
print("Old system method.")
class Adapter:
def __init__(self, old_system):
self.old_system = old_system
def new_method(self):
self.old_system.old_method()
# 测试适配器模式
adapter = Adapter(OldSystem())
adapter.new_method() # 输出:Old system method.
2. 桥接模式(Bridge)
定义:将抽象与实现分离,使它们可以独立变化。
应用场景:
- GUI 平台的适配
实现示例:
class Shape:
def __init__(self, color):
self.color = color
def draw(self):
pass
class Circle(Shape):
def draw(self):
print(f"Drawing a circle in {self.color}.")
class Square(Shape):
def draw(self):
print(f"Drawing a square in {self.color}.")
# 测试桥接模式
circle = Circle("red")
square = Square("blue")
circle.draw() # 输出:Drawing a circle in red.
square.draw() # 输出:Drawing a square in blue.
3. 装饰器模式(Decorator)
定义
动态地给对象添加功能,而不改变其结构。
应用场景
- 动态增强功能,如日志记录、权限验证。
- 替代继承扩展功能。
实现示例
# 基础类
class Component:
def operation(self):
pass
# 具体组件
class ConcreteComponent(Component):
def operation(self):
print("ConcreteComponent operation")
# 装饰器基类
class Decorator(Component):
def __init__(self, component):
self.component = component
def operation(self):
self.component.operation()
# 具体装饰器
class LoggingDecorator(Decorator):
def operation(self):
print("Logging operation")
self.component.operation()
# 测试装饰器模式
component = ConcreteComponent()
decorated = LoggingDecorator(component)
decorated.operation()
4. 组合模式(Composite)
定义
将对象组织成树形结构,以表示整体与部分的层次关系。
应用场景
- 文件系统(文件夹与文件的层级结构)。
- 用户界面中的控件树。
实现示例
# 组件基类
class Component:
def __init__(self, name):
self.name = name
def display(self, indent=0):
pass
# 叶子节点
class Leaf(Component):
def display(self, indent=0):
print(" " * indent + self.name)
# 组合节点
class Composite(Component):
def __init__(self, name):
super().__init__(name)
self.children = []
def add(self, component):
self.children.append(component)
def display(self, indent=0):
print(" " * indent + self.name)
for child in self.children:
child.display(indent + 2)
# 测试组合模式
root = Composite("Root")
folder1 = Composite("Folder1")
folder2 = Composite("Folder2")
file1 = Leaf("File1")
file2 = Leaf("File2")
root.add(folder1)
root.add(folder2)
folder1.add(file1)
folder2.add(file2)
root.display()
5. 外观模式(Facade)
定义
为子系统提供一个统一的接口,简化复杂子系统的使用。
应用场景
- 提供简化的 API 接口。
- 复杂子系统的封装。
实现示例
class SubsystemA:
def operation_a(self):
print("SubsystemA operation")
class SubsystemB:
def operation_b(self):
print("SubsystemB operation")
class Facade:
def __init__(self):
self.subsystem_a = SubsystemA()
self.subsystem_b = SubsystemB()
def operation(self):
print("Facade operation:")
self.subsystem_a.operation_a()
self.subsystem_b.operation_b()
# 测试外观模式
facade = Facade()
facade.operation()
6. 代理模式(Proxy)
定义
通过代理对象控制对目标对象的访问。
应用场景
- 安全访问控制。
- 延迟加载。
实现示例
class RealSubject:
def request(self):
print("RealSubject request")
class Proxy:
def __init__(self, real_subject):
self.real_subject = real_subject
def request(self):
print("Proxy control before real request")
self.real_subject.request()
# 测试代理模式
real_subject = RealSubject()
proxy = Proxy(real_subject)
proxy.request()
三、行为型模式
行为型模式关注对象之间的交互和职责分配,解决对象如何协作以完成更复杂的任务。
1. 责任链模式(Chain of Responsibility)
定义
将多个对象串成一条链,每个对象处理请求后可以将其传递给下一个对象,直到被处理完成。
应用场景
- 日志系统(不同级别的日志记录)。
- 表单验证。
实现示例
class Handler:
def __init__(self, successor=None):
self.successor = successor
def handle(self, request):
if self.successor:
self.successor.handle(request)
class ConcreteHandler1(Handler):
def handle(self, request):
if request == "task1":
print("Handler1 handled task1")
else:
super().handle(request)
class ConcreteHandler2(Handler):
def handle(self, request):
if request == "task2":
print("Handler2 handled task2")
else:
super().handle(request)
# 测试责任链模式
handler1 = ConcreteHandler1(ConcreteHandler2())
handler1.handle("task1") # 输出:Handler1 handled task1
handler1.handle("task2") # 输出:Handler2 handled task2
2. 命令模式(Command)
定义
将请求封装为对象,以支持撤销、重做等操作。
应用场景
- 文本编辑器的撤销和重做功能。
- GUI 按钮的命令执行。
实现示例
class Command:
def execute(self):
pass
class LightOnCommand(Command):
def execute(self):
print("The light is ON")
class LightOffCommand(Command):
def execute(self):
print("The light is OFF")
class RemoteControl:
def __init__(self):
self.history = []
def execute_command(self, command):
command.execute()
self.history.append(command)
# 测试命令模式
remote = RemoteControl()
on_command = LightOnCommand()
off_command = LightOffCommand()
remote.execute_command(on_command) # 输出:The light is ON
remote.execute_command(off_command) # 输出:The light is OFF
3. 迭代器模式(Iterator)
定义
提供一种方法顺序访问聚合对象中的元素,而不暴露其内部表示。
应用场景
- 自定义集合类的迭代支持。
实现示例
class MyIterator:
def __init__(self, collection):
self.collection = collection
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.collection):
value = self.collection[self.index]
self.index += 1
return value
else:
raise StopIteration
# 测试迭代器模式
collection = [1, 2, 3, 4]
iterator = MyIterator(collection)
for item in iterator:
print(item) # 输出:1 2 3 4
4. 观察者模式(Observer)
定义
对象间的依赖关系,当一个对象状态改变时,通知所有依赖者。
应用场景
- GUI 事件监听。
- 数据实时更新。
实现示例
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
class Observer:
def update(self, message):
print(f"Received: {message}")
# 测试观察者模式
subject = Subject()
observer1 = Observer()
observer2 = Observer()
subject.attach(observer1)
subject.attach(observer2)
subject.notify("Data updated")
5. 策略模式(Strategy)
定义
定义一组算法,让它们可以互相替换,且独立于使用它们的客户端。
应用场景
- 动态切换算法。
- AI 决策系统。
实现示例
class Strategy:
def execute(self):
pass
class StrategyA(Strategy):
def execute(self):
print("Executing Strategy A")
class StrategyB(Strategy):
def execute(self):
print("Executing Strategy B")
class Context:
def __init__(self, strategy):
self.strategy = strategy
def execute_strategy(self):
self.strategy.execute()
# 测试策略模式
context = Context(StrategyA())
context.execute_strategy() # 输出:Executing Strategy A
context.strategy = StrategyB()
context.execute_strategy() # 输出:Executing Strategy B
四、Python 动态语言特性衍生的模式
Python 的动态语言特性和强大的标准库,使其在设计模式的实现上更加简洁,同时也衍生了一些特有的设计模式。这些模式能够充分利用 Python 的灵活性,为开发者提供高效的解决方案。
1. 上下文管理器模式(Context Manager)
定义
上下文管理器通过 with
语句自动管理资源的获取和释放,比如文件打开与关闭、数据库连接等。
应用场景
- 文件操作
- 数据库连接管理
- 多线程锁管理
实现示例
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
# 测试上下文管理器模式
with FileManager("test.txt", "w") as f:
f.write("Hello, Python!")
2. 元类模式(Metaclass)
定义
元类是创建类的类,它允许动态修改类的行为。
应用场景
- 动态生成类
- 类的行为增强
实现示例
class Meta(type):
def __new__(cls, name, bases, dct):
dct["created_by_meta"] = True
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
# 测试元类模式
print(MyClass.created_by_meta) # 输出:True
3. 猴子补丁模式(Monkey Patching)
定义
猴子补丁是一种在运行时动态修改类或模块的方法。
应用场景
- 修复第三方库的缺陷
- 为现有模块添加新功能
实现示例
# 原始类
class Animal:
def speak(self):
print("Animal speaks.")
# 动态修改方法
def new_speak(self):
print("Animal now speaks differently.")
Animal.speak = new_speak
# 测试猴子补丁模式
animal = Animal()
animal.speak() # 输出:Animal now speaks differently.
4. 动态代理模式(Dynamic Proxy)
定义
动态代理允许开发者在运行时拦截并扩展对象的行为,而无需静态地修改其类定义。
应用场景
- 方法调用的日志记录
- 性能监控
实现示例
class RealObject:
def operation(self):
print("Real object operation")
class Proxy:
def __init__(self, real_object):
self.real_object = real_object
def operation(self):
print("Proxy before operation")
self.real_object.operation()
print("Proxy after operation")
# 测试动态代理模式
real_object = RealObject()
proxy = Proxy(real_object)
proxy.operation()
5. 注册模式(Registry)
定义
注册模式通过一个注册表动态管理类或函数实例,允许按需调用已注册的组件。
应用场景
- 插件系统
- 动态路由
实现示例
class Registry:
_registry = {}
@classmethod
def register(cls, name, obj):
cls._registry[name] = obj
@classmethod
def get(cls, name):
return cls._registry.get(name)
# 注册类
class PluginA:
def execute(self):
print("PluginA executed")
class PluginB:
def execute(self):
print("PluginB executed")
Registry.register("plugin_a", PluginA())
Registry.register("plugin_b", PluginB())
# 测试注册模式
plugin = Registry.get("plugin_a")
if plugin:
plugin.execute() # 输出:PluginA executed