Паттерны / Паттерны поведения
image

from abc import ABCabstractmethod


class Strategy(ABC):
    @abstractmethod
    def do_operation(self, a, b):
        pass


# ConcreteStrategy
class AddStrategy(Strategy):
    def do_operation(self, a, b):
        return a + b


# ConcreteStrategy
class SubtractStrategy(Strategy):
    def do_operation(self, a, b):
        return a - b


# Context
class Calc:
    def __init__(self):
        self.strategy = object

    def execute(self, a, b):
        if not isinstance(self.strategyStrategy):
            return 0
        return self.strategy.do_operation(a, b)

    def set_strategy(self, strategy):
        self.strategy = strategy


calc = Calc()
result1 = calc.execute(53)
# result1 is 0

calc.set_strategy(AddStrategy())
result2 = calc.execute(53)
# result2 is 8

calc.set_strategy(SubtractStrategy())
result3 = calc.execute(53)
# result3 is 2

print(f"{result1 = }")
print(f"{result2 = }")
print(f"{result3 = }")


Определяет семейство алгоритмов, инкапсулируя их и позволяя подставлять один вместо другого. Можно менять алгоритм независимо от клиента, который им пользуется.