mirror of
https://github.com/rjNemo/design-patterns
synced 2026-06-06 02:26:40 +00:00
40 lines
1.3 KiB
Python
40 lines
1.3 KiB
Python
from behavioral.strategy.strategy import Strategy
|
|
|
|
|
|
class Context:
|
|
"""
|
|
The Context defines the interface of interest to clients.
|
|
"""
|
|
|
|
def __init__(self, strategy: Strategy):
|
|
"""
|
|
Usually, the Context accepts a strategy through the constructor, but also provides a setter to change it at
|
|
runtime.
|
|
"""
|
|
self._strategy = strategy
|
|
|
|
@property
|
|
def strategy(self):
|
|
"""
|
|
The Context maintains a reference to one of the Strategy objects. The
|
|
Context does not know the concrete class of a strategy. It should work
|
|
with all strategies via the Strategy interface.
|
|
"""
|
|
return self._strategy
|
|
|
|
@strategy.setter
|
|
def strategy(self, strategy: Strategy):
|
|
"""
|
|
Usually, the Context allows replacing a Strategy object at runtime.
|
|
"""
|
|
self._strategy = strategy
|
|
|
|
def do_some_business_logic(self) -> None:
|
|
"""
|
|
The Context delegates some work to the Strategy object instead of implementing multiple versions of the
|
|
algorithm on its own.
|
|
"""
|
|
|
|
print("Context: Sorting data using the strategy (not sure how it'll do it)")
|
|
result = self._strategy.do_algorithm(["a", "b", "c", "d", "e"])
|
|
print(",".join(result))
|