策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。简而言之,策略模式就是根据不同的策略,选择对应不同的算法。
例如下面的示例,根据不同的国家,计算对应缴纳的税款。
TAX_PERCENT = .12
class TaxIN(object):
def __init__(self,):
self.country_code = "IN"
def __call__(self, billamount):
return billamount * TAX_PERCENT
class TaxUS(object):
def __init__(self,):
self.country_code = "US"
def __call__(self,billamount):
if billamount < 500:
return billamount * (TAX_PERCENT//2)
else:
return billamount * TAX_PERCENT
class TaxCalculator(object):
def __init__(self):
self._impls = [TaxIN(),TaxUS()]
def __call__(self, country, billamount):
"""select the strategy based on country parameter"""
for impl in self._impls:
if impl.country_code == country:
return impl(billamount)
else:
return None
tax_cal = TaxCalculator()
print(tax_cal("IN", 400), tax_cal("IN", 700))
print(tax_cal("US", 400), tax_cal("US", 700))
输出结果如下:
(48.0, 84.0)
(0.0, 84.0)