7.4. Strategy

7.4.1. Rationale

  • EN: Strategy

  • PL: Strategia

  • Type: object

7.4.2. Use Cases

  • Store images with compressor and filters

7.4.3. Problem

from dataclasses import dataclass


@dataclass
class ImageStorage:
    _compressor: str
    _filter: str

    def store(self, filename) -> None:
        if self._compressor == 'jpeg':
            print('Compressing using JPEG')
        elif self._compressor == 'png':
            print('Compressing using PNG')

        if self._filter == 'black&white':
            print('Applying Black&White filter')
        elif self._filter == 'high-contrast':
            print('Applying high contrast filter')

7.4.4. Design

  • Similar to State Pattern

  • No single states

  • Can have multiple states

  • Different behaviors are represented by strategy objects

../../_images/designpatterns-strategy-gof.png

7.4.5. Implementation

../../_images/designpatterns-strategy-usecase1.png
../../_images/designpatterns-strategy-usecase2.png
../../_images/designpatterns-strategy-vs-state.png
from abc import ABCMeta, abstractmethod


class Compressor(metaclass=ABCMeta):
    @abstractmethod
    def compress(self, filename: str) -> None:
        pass

class JPEGCompressor(Compressor):
    def compress(self, filename: str) -> None:
        print('Compressing using JPEG')

class PNGCompressor(Compressor):
    def compress(self, filename: str) -> None:
        print('Compressing using PNG')


class Filter(metaclass=ABCMeta):
    @abstractmethod
    def apply(self, filename) -> None:
        pass

class BlackAndWhiteFilter(Filter):
    def apply(self, filename) -> None:
        print('Applying Black and White filter')

class HighContrastFilter(Filter):
    def apply(self, filename) -> None:
        print('Applying high contrast filter')


class ImageStorage:
    def store(self, filename: str, compressor: Compressor, filter: Filter) -> None:
        compressor.compress(filename)
        filter.apply(filename)


if __name__ == '__main__':
    image_storage = ImageStorage()

    image_storage.store('myfile.jpg', JPEGCompressor(), BlackAndWhiteFilter())
    # Compressing using JPEG
    # Applying Black and White filter

    image_storage.store('myfile.png', PNGCompressor(), BlackAndWhiteFilter())
    # Compressing using PNG
    # Applying Black and White filter

7.4.6. Assignments