#!/usr/bin/env python # coding: utf-8 # # Strategy Pattern # 1. It belongs to Behavioral Pattern # 1. Also Known As **Policy Pattern** # 1. Used to control operations of some objects # # > **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 # # Shipping Module # 1. Supports FedEx, Postal, UPS # 1. Must be extendable # In[1]: from abc import ABCMeta, abstractmethod # ### Interface # In[2]: class IPaymentStrategy(metaclass = ABCMeta): @abstractmethod def calculate(self, order): pass # ### Payment Methods # In[3]: class FedExStrategy(IPaymentStrategy): def calculate(self, order): return order + 0.1 * order # In[4]: class PostalStrategy(IPaymentStrategy): def calculate(self, order): return order + 0.05 * order # In[5]: class UPSStrategy(IPaymentStrategy): def calculate(self, order): return order + 0.12 * order # ### Unified Payment Calculator # In[6]: class ShippingCost(): def __init__(self, payment_strategy): self._payment_strategy = payment_strategy def shipping_cost(self, order): return self._payment_strategy.calculate(order) # # Driver Program # In[7]: payment_strategy = FedExStrategy() cost_calc = ShippingCost(payment_strategy) print(cost_calc.shipping_cost(30)) # In[8]: payment_strategy = PostalStrategy() cost_calc = ShippingCost(payment_strategy) print(cost_calc.shipping_cost(30)) # In[9]: payment_strategy = UPSStrategy() cost_calc = ShippingCost(payment_strategy) print(cost_calc.shipping_cost(30))