策略模式
策略模式:
定义一系列算法,把它们一 一封装起来,并且使它们之间可以相互替换。此模式让算法的变化不会影响到使用算法的客户。
举例:电商领域根据客户的属性或订单中的商品计算折扣。
策略模式包含以下3个角色: Context(环境类) Strategy(抽象策略类) ConcreteStrategy(具体策略类)
from abc import ABC, abstractmethod
from collections import namedtuple
Customer = namedtuple('Customer', 'name fidelity')
class LineItem:
"""订单中单个商品的数量和单价"""
def __init__(self, product, quantity, price):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return self.price * self.quantity
class Order:
"""订单"""
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = list(cart)
sel