下面我将提供三种设计模式的Python实现示例:装饰器模式、策略模式和回调模式。
1. 装饰器模式
装饰器模式允许我们向一个对象添加新的功能,同时不改变其结构。在Python中,装饰器通常是一个函数,它接受一个函数作为参数并返回一个新的函数。
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello() # 输出: Something is happening before... Hello! ...after the function is called.
2. 策略模式
策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以互换。策略模式让算法独立于使用它的客户端。
from abc import ABC, abstractmethod
class Strategy(ABC):
@abstractmethod
def execute(self):
pass
class ConcreteStrategyA(Strategy):
def execute(self):
return "Executed strategy A"
class ConcreteStrategyB(Strategy):
def execute(self):
return "Executed strategy B"
class Context:
def __init__(self, strategy: Strategy):
self.strategy = strategy
def set_strategy(self, strategy: Strategy):
self.strategy = strategy
def do_operation(self):
return self.strategy.execute()
# 使用策略模式
context = Context(ConcreteStrategyA())
print(context.do_operation()) # 输出: Executed strategy A
context.set_strategy(ConcreteStrategyB())
print(context.do_operation()) # 输出: Executed strategy B
3. 回调函数
回调模式允许一个函数作为参数传递给另一个函数,然后在某个点被调用。这在事件处理、异步编程等领域非常常见。
def callback_function(data):
print(f"Callback received data: {data}")
def function_with_callback(data, callback):
print("Function is processing data.")
# 模拟数据处理
processed_data = data + " and processed it."
callback(processed_data)
function_with_callback("Function received", callback_function)
# 输出: Function is processing data. Callback received data: Function received and processed it.
在上述示例中,callback_function
是一个回调函数,它被作为参数传递给 function_with_callback
函数,并在数据处理完成后被调用。