๐
Implement Strategy Pattern
Table of contents
What is Iterator pattern for?
This pattern changes the behave of the object and like a state pattern but it has little difference.
We want platform that store image but before store the image compress image and apply filter on that. For this goal we use strategy pattern.
compressor_interface.py
Python
import abcclass CompresorInterface(metaclass=abc.ABCMeta):@classmethoddef __subclasshook__(cls, subclass):return (hasattr(subclass, 'compress') andcallable(subclass.compress) orNotImplemented)@abc.abstractmethoddef compress(self, fileName: str):raise NotImplementedError
filter_interface.py
Python
import abcclass FilterInterface(metaclass=abc.ABCMeta):@classmethoddef __subclasshook__(cls, subclass):return (hasattr(subclass, 'apply') andcallable(subclass.apply) orNotImplemented)@abc.abstractmethoddef apply(self, fileName: str):raise NotImplementedError
Now implement the compressor and filter
black_filter.py
Python
from filter_interface import FilterInterfaceclass BlackFilter(FilterInterface):def apply(self, fileName: str):print('Black filter apply on ' + fileName)
jpeg_compressor.py
Python
from compresor_interface import CompresorInterfaceclass JpegCompress(CompresorInterface):def compress(self, fileName: str):print('JPEG Compress' + fileName)
In this section we implement storage class
image_storage.py
Python
from compresor_interface import CompresorInterfacefrom filter_interface import FilterInterfaceclass ImageStorage:def store(self,fileName: str,compressor: CompresorInterface,filter: FilterInterface):compressor.compress(fileName)filter.apply(fileName)
main.py
Python
from image_storage import ImageStoragefrom jpeg_compressor import JpegCompressfrom black_filter import BlackFilterdef main():imageStorag = ImageStorage()imageStorag.store('mamad',JpegCompress(),BlackFilter())if __name__ == '__main__':main()
