Strategy Pattern
Strategy pattern is a behavioral design pattern that enables selecting an algorithm at runtime.
Python Example
from abc import ABC, abstractmethod
class Strategy(ABC):
@abstractmethod
def execute(self, data):
pass
class ConcreteStrategyA(Strategy):
def execute(self, data):
return sorted(data)
class ConcreteStrategyB(Strategy):
def execute(self, data):
return sorted(data)
class Context:
def __init__(self, strategy: Strategy):
self._strategy = strategy
@property
def strategy(self):
return self._strategy
@strategy.setter
def strategy(self, strategy: Strategy):
self._strategy = strategy
def arrange(self, data):
return list(self._strategy.execute(data))
data = [23, 78, 45, 8, 32, 56]
context = Context(ConcreteStrategyA())
print(context.arrange(data)) # Output: [8, 23, 32, 45, 56, 78]
context.strategy = ConcreteStrategyB()
print(context.arrange(data)) # Output: [78, 56, 45, 32, 23, 8]