策略模式python
时间: 2023-06-28 16:05:49 浏览: 43
策略模式是一种行为型设计模式,它允许你定义一系列算法,将每个算法封装起来,并且使它们可以互相替换。在使用策略模式时,你可以根据不同的需求,动态地切换算法。
在Python中,可以通过定义不同的函数或类来实现策略模式。下面是一个使用函数的示例:
```python
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: division by zero"
else:
return a / b
class Calculator:
def __init__(self, strategy):
self.strategy = strategy
def execute(self, a, b):
return self.strategy(a, b)
calculator = Calculator(add)
print(calculator.execute(2, 3)) # Output: 5
calculator.strategy = subtract
print(calculator.execute(2, 3)) # Output: -1
calculator.strategy = multiply
print(calculator.execute(2, 3)) # Output: 6
calculator.strategy = divide
print(calculator.execute(2, 0)) # Output: Error: division by zero
```
在上面的代码中,我们定义了四个函数,分别实现加法、减法、乘法和除法运算。然后我们定义了一个Calculator类,它有一个execute方法,接受两个参数a和b,然后调用strategy函数来执行对应的运算。
最后我们创建了一个Calculator对象,并将add函数作为策略传递给它。然后我们调用execute方法来执行加法运算。
接着我们动态地切换了策略,将subtract、multiply和divide函数依次作为策略传递给Calculator对象,并调用execute方法来执行对应的运算。
这就是一个简单的策略模式的示例。