Implementing Strategy pattern with Python
The Strategy pattern is a behavior design pattern that allows Selection algorithm at runtime. Python is an object-oriented programming language, which is very suitable for implementing Strategy pattern. The following is a simple example code that shows how to use Python to implement the Strategy pattern. ```python #Define Policy Interface class Strategy: def execute(self, num1, num2): pass #Define specific policy classes class AddStrategy(Strategy): def execute(self, num1, num2): return num1 + num2 class SubtractStrategy(Strategy): def execute(self, num1, num2): return num1 - num2 class MultiplyStrategy(Strategy): def execute(self, num1, num2): return num1 * num2 #Define Context Class class Context: def __init__(self, strategy): self.strategy = strategy def execute_strategy(self, num1, num2): return self.strategy.execute(num1, num2) #Usage examples context = Context(AddStrategy()) result = context.execute_strategy(5, 3) print(f"Add result: {result}") context = Context(SubtractStrategy()) result = context.execute_strategy(5, 3) print(f"Subtract result: {result}") context = Context(MultiplyStrategy()) result = context.execute_strategy(5, 3) print(f"Multiply result: {result}") ``` In the above example, we first defined the policy interface 'Strategy' and defined an 'execute' method in the interface. Then, we created three specific policy classes, namely 'AddStrategy', 'SubtractStrategy', and 'MultiplyStrategy', which implement the 'execute' method to execute different algorithms. Next, we define the context class' Context ', which receives a policy object in its constructor and provides an' execute '_ The strategy 'method is used to execute specific algorithms. Finally, we created an instance of 'Context' and executed different algorithms by passing in different policy objects, outputting the results. In this way, we can choose different policies at run time and apply them to specific problems, realizing the flexibility of Strategy pattern.