Middle
257
What is the Strategy pattern and how is it used in programming?
Answer from AI
sobes.tech AI
The Strategy pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the client to change the algorithm independently of the context in which it is used.
Main components of the pattern:
- Strategy: An interface or abstract class that declares a common method for all supported algorithms.
- Concrete Strategy: Classes that implement the Strategy interface and contain a specific implementation of an algorithm.
- Context: A class that contains a reference to a Strategy object and delegates the execution of the algorithm to it. The context does not know the specifics of the particular strategy; it only works with the Strategy interface.
Usage:
- Define a family of related algorithms.
- Create a Strategy interface or abstract class that defines a single method for executing these algorithms.
- Create Concrete Strategy classes that implement this interface/abstract class and contain specific algorithm implementations.
- Create a Context class that has a field to store a reference to a Strategy object and a method to execute the algorithm, delegating the call to this object.
- Client code creates Context and Concrete Strategy objects, then passes the desired Strategy object to the Context to execute a specific algorithm.
Advantages:
- Allows changing algorithms independently without modifying the Context code.
- Encapsulates each algorithm in a separate class, improving readability and modularity.
- Makes it easy to add new algorithms.
Example:
// Context
class Context:
def __init__(self, strategy):
self._strategy = strategy
def execute_strategy(self, data):
# Context delegates the execution to the strategy
return self._strategy.execute(data)
// Strategy Interface
class Strategy:
def execute(self, data):
# Abstract method for executing the algorithm
pass
// Concrete Strategy A
class ConcreteStrategyA(Strategy):
def execute(self, data):
# Implementation of algorithm A
return f"Algorithm A processed data: {data.upper()}"
// Concrete Strategy B
class ConcreteStrategyB(Strategy):
def execute(self, data):
# Implementation of algorithm B
return f"Algorithm B processed data: {data.lower()}"
// Client code
if __name__ == "__main__":
# Using Strategy A
context_a = Context(ConcreteStrategyA())
result_a = context_a.execute_strategy("Hello, World!")
print(result_a)
# Using Strategy B
context_b = Context(ConcreteStrategyB())
result_b = context_b.execute_strategy("HELLO, WORLD!")
print(result_b)