Strategy Pattern and inheriting boilerplate functionality

by Allie Fitter   Last Updated March 09, 2018 18:05 PM

I've read that when using the Strategy Pattern, you should stick to composition rather than inheritance. But does this mean that any inheritance at all is bad practice? If there is functionality to be shared between similar strategies is it anachronistic to implement a base class to encapsulate that functionality? Below is an example that could be better, but I hope illustrates my question.

from abc import ABC, abstractmethod


class AdditionStrategyInterface(ABC):    
    @abstractmethod
    def add(self, num1,  num2):
        raise NotImplementedError


class AdditionStrategy(AdditionStrategyInterface):
    def add(self, num1, num2):
        return num1 + num2


class AdditionPlusFourStrategyBase(AdditionStrategyInterface, ABC):
    def add_four(self, num):
        return num + 4

    @abstractmethod
    def add(self, num1, num2):
        raise NotImplementedError


class AdditionPlusFourStrategy(AdditionPlusFourStrategyBase):
    def add(self, num1, num2):
        return self.add_four(num1 + num2)


class AdditionPlusEightStrategy(AdditionPlusFourStrategyBase):
    def add(self, num1, num2):
        return self.add_four(self.add_four(num1 + num2))


Related Questions


Inheritance vs 'specification' by fields

Updated September 13, 2017 21:05 PM

What would be the best option in this scenario?

Updated July 27, 2017 17:05 PM


Implementing strategy pattern via configuration

Updated February 28, 2018 08:05 AM