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

要求

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

思路

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

  • 类变量与实例变量
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,961评论 5 473
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,444评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,009评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,082评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,101评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,271评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,738评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,395评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,539评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,434评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,481评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,160评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,749评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,816评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,038评论 1 256
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,548评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,140评论 2 341

推荐阅读更多精彩内容