美文网首页
【设计模式】策略模式之商场促销

【设计模式】策略模式之商场促销

作者: flowerAO | 来源:发表于2018-04-30 11:09 被阅读0次

    要求

    实现一个商场收银软件,营业员根据客户购买的商品单价和数量,向客户收费。

    思路

    Iter1 初始草稿

    每个商品单价*数量,相加。

    #!/usr/bin/python
    # coding:utf-8
    
    class Cashier:
        total = 0
        def submit(self, perPrice, perNum):
            totalPrices = float(perPrice) * float(perNum)
            self.total += totalPrices
            print "单价:", perPrice, "数量:", perNum, "合计: ", totalPrices
            
    
    问题:
    • 如果商场要搞各种各样促销活动,怎么做呢?

    Iter2 增加打折需求

    • 实现方式
      • choice 1: 在总价后面乘以折扣。但之后搞不同活动,打不同折扣需要频繁修改代码。
      • choice 2: 增加选择框,将所有折扣以列表方式呈现,进行选择。
    #!/usr/bin/python
    # coding:utf-8
    
    class Cashier:
        total = 0
        selectedAct = 0
        def submit(self, perPrice, perNum, selectedAct):
            switcher = {
                0: float(perPrice) * float(perNum),
                1: float(perPrice) * float(perNum) * 0.8,
                2: float(perPrice) * float(perNum) * 0.7,
                3: float(perPrice) * float(perNum) * 0.5
            }
            totalPrices = switcher[selectedAct]
            self.total += totalPrices
            print "单价:", perPrice, "数量:", perNum, "合计: ", totalPrices
    
        def activities(self):
            discount = {0: "正常收费", 1:"打八折", 2:"打七折", 3:"打五折"}
            selectedAct = 0
    
    问题:
    • 重复代码太多,考虑重构
    • 商场活动加大,增加满减促销活动

    Iter3 简单工厂实现

    #!/usr/bin/python
    # coding:utf-8
    import math
    
    
    class CashSuper:
        def acceptCash(self, money):
            return money
    
    
    class CashNormal(CashSuper):
        def acceptCash(self, money):
            return money
    
    
    class CashRebate(CashSuper):
        def __init__(self, moneyRebate):
            self.moneyRebate = float(moneyRebate)
    
        def acceptCash(self, money):
            return money * self.moneyRebate
    
    
    class CashReturn(CashSuper):
        def __init__(self, moneyCondition, moneyReturn):
            self.moneyCondition = float(moneyCondition)
            self.moneyReturn = float(moneyReturn)
    
        def acceptCash(self, money):
            if money >= self.moneyCondition:
                return money - math.floor(money / self.moneyCondition) * self.moneyReturn
            return money
    
    
    class CashFactory:
        @staticmethod
        def createCashAccept(type):
            switcher = {
                "正常收费": CashNormal(),
                "满300减100": CashReturn("300", "100"),
                "打8折": CashRebate("0.8"),
            }
            return switcher[type]
    
    
    def submit(perPrice, perNum, selectedAct):
        global total
        csuper = CashFactory.createCashAccept(selectedAct)
        totalPrices = csuper.acceptCash(perNum * perPrice)
        total += totalPrices
        print "单价:", totalPrices, "数量:", perNum, "合计: ", totalPrices
    
    
    if __name__ == "__main__":
        total = 0
        submit(1000, 2, "打8折")
        submit(1000, 2, "满300减100")
    
    问题:
    • 如果算法经常变动呢?
      简单工厂只解决了对象创建的问题,商场可能经常性更改活动,每次维护或扩展收费方式都要改动这个工厂,所有代码需要重新编译部署

    Iter4 策略模式是什么?

    定义:策略模式定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

    #!/usr/bin/python
    # coding:utf-8
    
    class Strategy:
        def AlgorithmInterface(self):
            pass
    
    
    class ConcreteStrategyA(Strategy):
        def AlgorithmInterface(self):
            print "算法A实现"
    
    
    class ConcreteStrategyB(Strategy):
        def AlgorithmInterface(self):
            print "算法B实现"
    
    
    class ConcreteStrategyC(Strategy):
        def AlgorithmInterface(self):
            print "算法C实现"
    
    
    class Context:
        def __init__(self, strategy):
            self.strategy = strategy
    
        def ContextInterface(self):
            self.strategy.AlgorithmInterface()
    
    if __name__ == "__main__":
        context = Context(ConcreteStrategyA())
        context.ContextInterface()
    
        context = Context(ConcreteStrategyB())
        context.ContextInterface()
    
        context = Context(ConcreteStrategyC())
        context.ContextInterface()
    

    Iter5 策略模式实现

    #!/usr/bin/python
    # coding:utf-8
    import math
    
    
    class CashSuper:
        def acceptCash(self, money):
            return money
    
    
    class CashNormal(CashSuper):
        def acceptCash(self, money):
            return money
    
    
    class CashRebate(CashSuper):
        def __init__(self, moneyRebate):
            self.moneyRebate = float(moneyRebate)
    
        def acceptCash(self, money):
            return money * self.moneyRebate
    
    
    class CashReturn(CashSuper):
        def __init__(self, moneyCondition, moneyReturn):
            self.moneyCondition = float(moneyCondition)
            self.moneyReturn = float(moneyReturn)
    
        def acceptCash(self, money):
            if money >= self.moneyCondition:
                return money - math.floor(money / self.moneyCondition) * self.moneyReturn
            return money
    
    
    class CashContext:
        def __init__(self, strategy):
            self.strategy = strategy
    
        def getresult(self, money):
            return self.strategy.acceptCash(money)
    
    
    class CashFactory:
        @staticmethod
        def createCashAccept(type):
            switcher = {
                "正常收费": CashNormal(),
                "满300减100": CashReturn("300", "100"),
                "打8折": CashRebate("0.8"),
            }
            return switcher[type]
    
    
    def submit(perPrice, perNum, selectedAct):
        global total
        switcher = {
            "正常收费": CashContext(CashNormal()),
            "满300减100": CashContext(CashReturn("300", "100")),
            "打8折": CashContext(CashRebate("0.8")),
        }
        cc = switcher[selectedAct]
    
        totalPrices = cc.getresult(perNum * perPrice)
        total += totalPrices
        print "单价:", perPrice, "数量:", perNum, "合计: ", totalPrices
    
    
    if __name__ == "__main__":
        total = 0
        submit(1000, 2, "打8折")
        submit(1000, 2, "满300减100")
    
    
    问题:
    • 考虑将判断的过程从客户端移走

    Iter5 策略模式与简单工厂结合

    即将context类中初始化传入的值从对象,变为字符串。

    #!/usr/bin/python
    # coding:utf-8
    import math
    
    
    class CashSuper:
        def acceptCash(self, money):
            return money
    
    
    class CashNormal(CashSuper):
        def acceptCash(self, money):
            return money
    
    
    class CashRebate(CashSuper):
        def __init__(self, moneyRebate):
            self.moneyRebate = float(moneyRebate)
    
        def acceptCash(self, money):
            return money * self.moneyRebate
    
    
    class CashReturn(CashSuper):
        def __init__(self, moneyCondition, moneyReturn):
            self.moneyCondition = float(moneyCondition)
            self.moneyReturn = float(moneyReturn)
    
        def acceptCash(self, money):
            if money >= self.moneyCondition:
                return money - math.floor(money / self.moneyCondition) * self.moneyReturn
            return money
    
    
    class CashContext:
        def __init__(self, type):
            switcher = {
                "正常收费": CashNormal(),
                "满300减100": CashReturn("300", "100"),
                "打8折": CashRebate("0.8"),
            }
            self.cs = switcher[type]
    
        def acceptCash(self, money):
            return self.cs.acceptCash(money)
    
    
    def submit(perPrice, perNum, selectedAct):
        global total
        csuper = CashContext(selectedAct)
        totalPrices = csuper.acceptCash(perNum * perPrice)
        total += totalPrices
        print "单价:", perPrice, "数量:", perNum, "合计: ", totalPrices
    
    
    if __name__ == "__main__":
        total = 0
        submit(1000, 2, "打8折")
        submit(1000, 2, "满300减100")
    
    
    

    简单工厂、策略模式、简单工厂+策略模式 对比

    #简单工厂
    csuper = CashFacroty.createCashAccept(selectedAct)
    totalPrices = csuper.acceptCash(perNum * perPrice)
    
    #策略模式
    swithcer = {
      "...": CashContext(CashNormal()),
      "...": CashContext(CashReturn("400","200")),
    }
    cc = swithcer[selectedAct]
    totalPrices = cc.getresult(perNum * perPrice)
    
    #简单工厂+策略模式
    csuper = CashContext(selectedAct)
    totalPrices = csuper.acceptCash(perNum * perPrice)
    
    

    策略模式与简单工厂区别:context还知道功能类的接口,而简单工厂不知道。策略模式,外部知道功能类的存在。两者结合,使得外部不知道功能类的存在,就直接使用相关的功能。

    策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。

    策略模式的strategy类层次为Context定义了一系列可供重用的算法或行为。继承有助于析取出这些算法中的公共功能。(即获得计算费用的结果,这使得算法间有了抽象的父类)

    简化单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。

    问题:
    • 若需要增加一种算法,比如“满200送50”,那就必须更改CashContext中的选择代码,有没有更低的维护成本?。引用 反射技术

    UML图

    SimpleFactory

    细碎python

    • 类变量与实例变量

    相关文章

      网友评论

          本文标题:【设计模式】策略模式之商场促销

          本文链接:https://www.haomeiwen.com/subject/osjulftx.html