Summary
- It takes a family of Algos
- Encapsulates each one
- And make them interchangeable with each other
- Algos may vary independently
- No more if-elif
- Each Algo can be unit tested as well as system tested
from abc import ABCMeta, abstractmethod
class IPaymentStrategy(metaclass = ABCMeta):
@abstractmethod
def calculate(self, order):
pass
class FedExStrategy(IPaymentStrategy):
def calculate(self, order):
return order + 0.1 * order
class PostalStrategy(IPaymentStrategy):
def calculate(self, order):
return order + 0.05 * order
class UPSStrategy(IPaymentStrategy):
def calculate(self, order):
return order + 0.12 * order
class ShippingCost():
def __init__(self, payment_strategy):
self._payment_strategy = payment_strategy
def shipping_cost(self, order):
return self._payment_strategy.calculate(order)
payment_strategy = FedExStrategy()
cost_calc = ShippingCost(payment_strategy)
print(cost_calc.shipping_cost(30))
33.0
payment_strategy = PostalStrategy()
cost_calc = ShippingCost(payment_strategy)
print(cost_calc.shipping_cost(30))
31.5
payment_strategy = UPSStrategy()
cost_calc = ShippingCost(payment_strategy)
print(cost_calc.shipping_cost(30))
33.6