from collections import namedtuple
def reducer(arg1, arg2, strategy=None):
if strategy == "addition":
return arg1 + arg2
elif strategy == "subtraction":
return arg1 - arg2
else:
return "Strategy not implemented"
if __name__ == '__main__':
print(reducer(4, 6))
print(reducer(4, 6, "addition"))
print(reducer(4, 6, "subtraction"))
# 防止if语句的无序蔓延和引发代码布局恶化的风险,使用策略模式
def executor(arg1, arg2, func=None):
if func is None:
return "Strategy not implemented"
return func(arg1, arg2)
def strategy_addition(arg1, arg2):
return arg1 + arg2
def strategy_subtraction(arg1, arg2):
return arg1 - arg2
if __name__ == '__main__':
print(executor(4, 6))
print(executor(4, 6, strategy_addition))
print(executor(4, 6, strategy_subtraction))
# Order 类和使用函数实现的折扣策略
Customer = namedtuple('Customer', 'name fidelity')
promos = []
def promotion(promo_func):
promos.append(promo_func)
return promo_func
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)
self.promotion = promotion
def total(self):
if not hasattr(self, '__total'):
self.__total = sum(item.total() for item in self.cart)
return self.__total
def due(self):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
@promotion
def fidelity_promo(order):
"""为积分为1000或以上的顾客提供5%折扣"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
@promotion
def bulk_item_promo(order):
"""单个商品为20个或以上时提供10%折扣"""
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
@promotion
def large_order_promo(order):
"""订单中的不同商品达到10个或以上时提供7%折扣"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
def best_promo(order):
"""选择可用的最佳折扣"""
return max(promo(order) for promo in promos)
if __name__ == '__main__':
joe = Customer('John Doe', 0)
ann = Customer('Ann Smith', 1100)
cart = [LineItem('banana', 4, .5),
LineItem('apple', 10, 1.5),
LineItem('watermellon', 5, 5.0)]
Order(joe, cart, fidelity_promo) # <Order total: 42.00 due: 42.00>
Order(ann, cart, fidelity_promo) # <Order total: 42.00 due: 39.90>
banana_cart = [LineItem('banana', 30, .5),
LineItem('apple', 10, 1.5)]
Order(joe, banana_cart, bulk_item_promo) # <Order total: 30.00 due: 28.50>
long_order = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]
Order(joe, long_order, large_order_promo) # <Order total: 10.00 due: 9.30>
Order(joe, cart, large_order_promo) # <Order total: 42.00 due: 42.00>
Python设计模式--策略模式
最新推荐文章于 2024-08-28 16:14:15 发布