0

I was tinkering with an example of the strategy pattern that can be found below.

from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List

class Context():

    def __init__(self,strategy: Strategy) -> None:
        self._strategy = strategy

    @property
    def strategy(self) -> Strategy:
        return self._strategy
    

    @strategy.setter
    def strategy(self, strategy: Strategy) -> None:
        self._strategy = strategy
    
    def do_some_business_logic(self) -> None:

        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))



class Strategy(ABC):

    @abstractmethod 
    def do_algorithm(self, data:List):
        pass



class ConcreteStrategyA(Strategy):
    def do_algorithm(self, data: List) -> List:
        return sorted(data)


class ConcreteStrategyB(Strategy):
    def do_algorithm(self, data: List) -> List:
        return reversed(sorted(data))


if __name__ == "__main__":
    context = Context(ConcreteStrategyA())
    print("Client: Strategy is set to normal sorting.")
    context.do_some_business_logic()
    print()

    print("Client: Strategy is set to reverse sorting.")
    context.strategy = ConcreteStrategyB()
    context.do_some_business_logic()

Why are ABC and abstract method used? I tried to take it away from the code and the code still works. What does it add?

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
patrik muniak
  • 86
  • 1
  • 9
  • `abstractmethod` is to enforce the children class to implement that method – azro Sep 06 '20 at 10:46
  • I found the source code that you used, and it is worthy of passing on the link: https://refactoring.guru/design-patterns/strategy/python/example – rajah9 Sep 06 '20 at 16:15

1 Answers1

1

why ABC and abstract method is used?

In OOP, it's called interface. It defines the function prototype that inherited class need to implement. In your example, those ConcreteStrategyA and ConcreteStrategyB are concrete classes that inherited from the Strategy interface.

why is an empty Strategy class used?

It's not empty. It defines the interface that derived classes are inherited from.

artm
  • 16,141
  • 4
  • 27
  • 46
  • ok, I think I get it now. So basically the aim of the interface Strategy is to reduce the likelihood of bugs. For example in this case, without the Strategy interface, it would give too much freedom to a developer which would lead to a higher risk of bugs. is this correct? – patrik muniak Sep 06 '20 at 11:04
  • That could be one interpretation. For the two main uses of interface, you can have a look at https://www.cs.utah.edu/~germain/PPS/Topics/interfaces.html#:~:text=Interfaces%20in%20Object%20Oriented%20Programming,have%20a%20start_engine()%20action. – artm Sep 06 '20 at 11:51