设计模式-行为型模式,策略模式(15)
2018-03-08 13:38
253 查看
策略模式(Strategy pattern)鼓励使用多种算法来解决一个问题,其杀手级特性是能够在运
行时透明地切换算法(客户端代码对变化无感知)。因此,如果你有两种算法,并且知道其中一
种对少量输入效果更好,另一种对大量输入效果更好,则可以使用策略模式在运行时基于输入数
据决定使用哪种算法
看以看到策略模式和工厂模式很像。但其实两个的差别很微妙,工厂模式是直接创建具体的对象并用该对象去执行相应的动作。简单工厂模式侧重于生成对象。
而策略模式将这个操作给了Context类,没有创建具体的对象,实现的代码的进一步封装,客户端代码并不需要知道具体的实现过程。 策略模式中注重具体算法的实现。
一个创建型模式,一个行为行模式。
行时透明地切换算法(客户端代码对变化无感知)。因此,如果你有两种算法,并且知道其中一
种对少量输入效果更好,另一种对大量输入效果更好,则可以使用策略模式在运行时基于输入数
据决定使用哪种算法
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'Andy' ''' 大话设计模式 设计模式——策略模式 策略模式(strategy):它定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户 ''' #现金收费抽象类 class CashSuper(object): def accept_cash(self,money): pass #正常收费子类 class CashNormal(CashSuper): def accept_cash(self,money): return money #打折收费子类 class CashRebate(CashSuper): def __init__(self,discount=1): self.discount = discount def accept_cash(self,money): return money * self.discount #返利收费子类 class CashReturn(CashSuper): def __init__(self,money_condition=0,money_return=0): self.money_condition = money_condition self.money_return = money_return def accept_cash(self,money): if money>=self.money_condition: return money - (money / self.money_condition) * self.money_return return money #具体策略类 class Context(object): def __init__(self,csuper): self.csuper = csuper def GetResult(self,money): return self.csuper.accept_cash(money) if __name__ == '__main__': money = input("原价: ") strategy = {} strategy[1] = Context(CashNormal()) strategy[2] = Context(CashRebate(0.8)) strategy[3] = Context(CashReturn(100,10)) mode = input("选择折扣方式: 1) 原价 2) 8折 3) 满100减10: ") if mode in strategy: csuper = strategy[mode] else: print "不存在的折扣方式" csuper = strategy[1] print "需要支付: ",csuper.GetResult(money)
看以看到策略模式和工厂模式很像。但其实两个的差别很微妙,工厂模式是直接创建具体的对象并用该对象去执行相应的动作。简单工厂模式侧重于生成对象。
而策略模式将这个操作给了Context类,没有创建具体的对象,实现的代码的进一步封装,客户端代码并不需要知道具体的实现过程。 策略模式中注重具体算法的实现。
一个创建型模式,一个行为行模式。
相关文章推荐
- 设计模式-行为型- 策略模式(Strategy)
- 设计模式 (一)——策略模式(Strategy,行为型)
- 设计模式(二)—策略模式(行为型)
- Java设计模式(15)——行为模式之策略模式(Strategy)
- 23种设计模式(15)_行为型_迭代器模式(Iterator Pattern)
- java设计模式之行为型模式-策略模式
- Java设计模式_行为型_策略模式_工作还是休息
- 设计模式:Strategy 策略模式 -- 行为型
- 设计模式(15)--Interpreter(解释器模式)--行为型
- 设计模式笔记 22. Strategy 策略模式(行为型模式)
- [.net 面向对象程序设计深入](26)实战设计模式——策略模式 Strategy (行为型)
- 行为型设计模式之模板方法(TEMPLATE METHOD)模式 ,策略(Strategy )模式
- 设计模式 ( 十八 ) 策略模式Strategy(对象行为型)
- 设计模式22:Strategy 策略模式(行为型模式)
- 行为型的设计模式-策略模式
- 设计模式之七:Strategy(策略)—对象行为型模式
- 设计模式-行为型模式-策略模式
- 23种设计模式4--行为型模式(策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式)
- java设计模式--行为型模式--策略模式
- 【JavaScript设计模式】行为型设计模式--策略模式