Junior — Middle
How can the strategy pattern be implemented in Python programming?
sobes.tech AI
Answer from AI
The strategy pattern allows changing the behavior algorithms of an object at runtime by encapsulating them into separate classes or functions.
In Python, this can be implemented using classes or functions passed as strategies.
Example with classes:
class Strategy:
def execute(self, data):
pass
class StrategyA(Strategy):
def execute(self, data):
return sorted(data)
class StrategyB(Strategy):
def execute(self, data):
return list(reversed(data))
class Context:
def __init__(self, strategy: Strategy):
self._strategy = strategy
def set_strategy(self, strategy: Strategy):
self._strategy = strategy
def do_action(self, data):
return self._strategy.execute(data)
context = Context(StrategyA())
print(context.do_action([3,1,2])) # [1, 2, 3]
context.set_strategy(StrategyB())
print(context.do_action([3,1,2])) # [2, 1, 3]
This way, you can easily change the behavior of an object without modifying its code.