Sobes.tech
Junior — Middle

Have you had experience using the Strategy pattern in your projects?

sobes.tech AI

Answer from AI

The Strategy pattern allows defining a family of algorithms, encapsulating each one, and making them interchangeable. In Python, I used this pattern, for example, to implement different data sorting methods depending on conditions.

Example:

class SortStrategy:
    def sort(self, data):
        pass

class QuickSort(SortStrategy):
    def sort(self, data):
        return sorted(data)  # simplified

class BubbleSort(SortStrategy):
    def sort(self, data):
        # implementation of bubble sort
        for i in range(len(data)):
            for j in range(len(data)-1-i):
                if data[j] > data[j+1]:
                    data[j], data[j+1] = data[j+1], data[j]
        return data

class Sorter:
    def __init__(self, strategy: SortStrategy):
        self._strategy = strategy

    def sort(self, data):
        return self._strategy.sort(data)

# Usage
sorter = Sorter(QuickSort())
print(sorter.sort([5, 3, 6, 2]))

sorter = Sorter(BubbleSort())
print(sorter.sort([5, 3, 6, 2]))

This approach allows changing the sorting algorithm without modifying client code.