[OOP 设计模式] Strategy Design Pattern

Intent 目的

  • Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
  • Capture the abstraction in an interface, bury implementation details in derived classes.

我的理解是:Strategy pattern 延用了 “open close principle” 。 通过一系列encapsulation, 保证每个class都只有一项主要任务。让client自由选择用哪一个class。

Problem Statement 需解决的问题

Implement image storage with functionalities such as compress and filter
实现一个储存图片的class, 有压缩和滤镜功能

❌ 示例1

"""
* Class gets bulky and hard to maintain over time
* It is hard to support more compressors and filters
"""
class ImageStorage:

    def __init__(self):
        self._compressor = None
        self._filter = None

    def store(self, fileName: str):
        if self._compressor == 'jpeg':
            print('Compressing using jpeg')

        if self._compressor == 'png':
            print('Compressing using png')

        if self._filter == 'B&W':
            print('Applying B&W filter.')

        if self._filter == 'high-contrast':
            print('Applying high-contrast filter.')

✅ 示例 Iterator Pattern

Screen Shot 2020-12-14 at 7.23.26 AM.png
from abc import ABC, abstractmethod


class Compressor(ABC):

    @abstractmethod
    def compress(self, img: str):
        raise NotImplementedError


class JpegCompressor(Compressor):

    def compress(self, img: str):
        print(f'Compressing {img} using jpeg.')


class PngCompressor(Compressor):

    def compress(self, img: str):
        print(f'Compressing {img} using png.')


class Filter(ABC):

    @abstractmethod
    def filter(self, img: str):
        raise NotImplementedError


class BWFilter(Filter):

    def filter(self, img: str):
        print(f'Filtering {img} using b&w.')


class HighContrastFilter(Filter):

    def filter(self, img: str):
        print(f'Filtering {img} using high contrast.')


class ImageStorage:

    def __init__(self, compressor: Compressor, filter: Filter):
        self._compressor = compressor
        self._filter = filter

    def store(self, fileName: str):
        self._compressor.compress(fileName)
        self._filter.filter(fileName)


def main():
    image_store = ImageStorage(compressor=JpegCompressor(), filter=BWFilter())
    image_store.store('a')

参考

Code with Mosh
Source Making

你可能感兴趣的:([OOP 设计模式] Strategy Design Pattern)