python设计模式(4)

系列文章目录

提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档


需求

请帮小李写一个订单结算模块,要求支持多种结算策略:

  • 原价
  • 打 X 折
  • 满减,满 X 元减 Y 元

请注意,商品有多种类型,每种类型可能会参与不同的活动,自然需要支持不同的结算策略。

考虑

  1. 工厂方法模式创建不同的商品 “0”:“正常收费”,“1”:“打8折”,“2”:“满300返100”,“3”:“打折满减混合”

  2. 策略模式计算不同商品的价格

  3. 之后可以考虑给价格做一个类, 用工厂方法穿件不同的价格种类,而不是直接创建商品+价格

代码及实现

from abc import ABCMeta, abstractmethod
from collections import defaultdict


class CashSuper(metaclass=ABCMeta):
    @abstractmethod
    def accept_cash(self, money):
        raise NotImplementedError("not implemented")


# 正常收费
class CashNormal(CashSuper):
    def accept_cash(self, money):
        return money


# 打折收费
class CashRebate(CashSuper):
    def __init__(self, moneyRebateStr="1"):
        self.__moneyRebate = float(moneyRebateStr)

    def accept_cash(self, money):
        return money * self.__moneyRebate


# 返利收费
class CashReturn(CashSuper):
    def __init__(self, moneyConditionStr="0", moneyReturnStr="0"):
        self.__moneyCondition = float(moneyConditionStr)
        self.__moneyReturn = float(moneyReturnStr)

    def accept_cash(self, money):
        result = money
        if (money >= self.__moneyCondition):
            result = money - money // self.__moneyCondition * self.__moneyReturn
        return result


class CashRebateAndReturn(CashSuper):
    def __init__(self, moneyRebateStr="1", moneyConditionStr="0", moneyReturnStr="0"):
        self.__moneyRebate = float(moneyRebateStr)
        self.__moneyCondition = float(moneyConditionStr)
        self.__moneyReturn = float(moneyReturnStr)

    def accept_cash(self, money):
        money = money * self.__moneyRebate
        if (money >= self.__moneyCondition):
            result = money - money // self.__moneyCondition * self.__moneyReturn
        return result


class Product(metaclass=ABCMeta):
    def __init__(self, product_id, product_name, price):
        self.product_id = product_id
        self.product_name = product_name
        self.price = price


class NormalProduct(Product):

    def __init__(self, product_id, product_name, price):
        super().__init__(product_id, product_name, price)
        self.typ = "正常收费"


class RebateProduct(Product):
    def __init__(self, product_id, product_name, price):
        super().__init__(product_id, product_name, price)
        self.typ = "打8折"


class ReturnProduct(Product):
    def __init__(self, product_id, product_name, price):
        super().__init__(product_id, product_name, price)
        self.typ = "满300返100"


class RebateAndReturnProduct(Product):
    def __init__(self, product_id, product_name, price):
        super().__init__(product_id, product_name, price)
        self.typ = "折完减"


class IFactory(metaclass=ABCMeta):
    def __init__(self, product_id, product_name, price):
        self.product_id = product_id
        self.product_name = product_name
        self.price = price

    @abstractmethod
    def create_product(self):
        raise NotImplementedError


class NormalProductFactory(IFactory):
    def __init__(self, product_id, product_name, price):
        super().__init__(product_id, product_name, price)

    @property
    def create_product(self):
        return NormalProduct(self.product_id, self.product_name, self.price)


class RebateProductFactory(IFactory):
    def __init__(self, product_id, product_name, price):
        super().__init__(product_id, product_name, price)

    @property
    def create_product(self):
        return RebateProduct(self.product_id, self.product_name, self.price)


class ReturnProductFactory(IFactory):
    def __init__(self, product_id, product_name, price):
        super().__init__(product_id, product_name, price)

    @property
    def create_product(self):
        return ReturnProduct(self.product_id, self.product_name, self.price)


class RebateAndReturnProductFactory(IFactory):
    def __init__(self, product_id, product_name, price):
        super().__init__(product_id, product_name, price)

    @property
    def create_product(self):
        return RebateAndReturnProduct(self.product_id, self.product_name, self.price)


class CashContext(object):
    map_dict = {"正常收费": CashNormal(),
                "打8折": CashRebate("0.8"),
                "满300返100": CashReturn("300", "100"),
                "折完减": CashRebateAndReturn("0.8", "300", "100")
                }

    def __init__(self, product_dict=None):
        self.product_dict = defaultdict(list)

    def add_product(self, product):
        self.product_dict[product.typ].append(product)

    def get_result(self):
        result = 0
        for typ, product_list in self.product_dict.items():
            money = sum([p.price for p in product_list])
            result += self.map_dict.get(typ).accept_cash(money)
        return result


# 工厂方法模式创建不同的商品 "0":"正常收费","1":"打8折","2":"满300返100","3":"打折满减混合"

# 策略模式计算不同商品的价格

# 之后可以考虑给价格做一个类, 用工厂方法穿件不同的价格种类,而不是直接创建商品+价格

if __name__ == '__main__':
    cc = CashContext()
    cc.add_product(NormalProductFactory("001", "流行外套", 1800).create_product)
    cc.add_product(RebateProductFactory("002", "普通外套", 1600).create_product)
    cc.add_product(ReturnProductFactory("003", "过季外套", 1000).create_product)
    cc.add_product(RebateAndReturnProductFactory("004", "处理外套", 800).create_product)
    cc.add_product(RebateProductFactory("005", "普通套衫", 2000).create_product)
    cc.add_product(NormalProductFactory("006", "流行套衫", 2800).create_product)
    cc.add_product(ReturnProductFactory("007", "过季套衫", 1500).create_product)
    cc.add_product(RebateAndReturnProductFactory("008", "处理套衫", 1200).create_product)
    print(cc.product_dict)
    print(cc.get_result())
    print(4600 + 3600 * 0.8 + 2500 - (2500 // 300 * 100) + (1200 + 800) * 0.8 - (1200 + 800) * 0.8 // 300 * 100)


运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值