赞
踩
策略模式是一种行为设计模式,它定义了一系列算法,将每个算法封装起来,并使它们可以互相替换。
在需要根据不同情况选择不同算法或策略,规避不断开发新需求后,代码变得非常臃肿难以维护管理。
- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- __doc__ = """
- 策略模式
- 例:商场优惠活动,选择不同的优惠策略,最后计算的价格也不同。而如果增加新算法,只需增加一个策略类,无需修改现有代码
- """
-
- from abc import ABC, abstractmethod
-
-
- class DiscountStrategy(ABC):
- """抽象策略类"""
-
- @abstractmethod
- def apply_discount(self, price):
- pass
-
-
- class PercentDiscount(DiscountStrategy):
- """具体策略类:打折策略"""
-
- def __init__(self, discount_percent):
- self.discount_percent = discount_percent
-
- def apply_discount(self, price):
- return price * (1 - self.discount_percent / 100)
-
-
- class FullReduction(DiscountStrategy):
- """具体策略类:满减策略"""
-
- def __init__(self, full_price, reduction_price):
- self.full_price = full_price
- self.reduction_price = reduction_price
-
- def apply_discount(self, price):
- return price - (price // self.full_price) * self.reduction_price
-
-
- class Promotion:
- """上下文类:商场促销"""
-
- def __init__(self, discount_strategy):
- self.discount_strategy = discount_strategy
-
- def apply_discount(self, price):
- return self.discount_strategy.apply_discount(price)
-
-
- if __name__ == "__main__":
- """
- 打折后价格:80.0
- 满减后价格:100
- """
- # 商品原价
- original_price = 100
- # 选择打折策略,打8折
- promotion = Promotion(PercentDiscount(20))
- discounted_price = promotion.apply_discount(original_price)
- print(f"打折后价格:{discounted_price}")
-
- # 选择满减策略,满200减50
- promotion = Promotion(FullReduction(200, 50))
- discounted_price = promotion.apply_discount(original_price)
- print(f"满减后价格:{discounted_price}")
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。