您的位置:首页 > 编程语言 > Python开发

【设计模式】二 、策略模式及与简单工厂模式的区别

2015-04-29 21:04 274 查看
在设计模式一中,我们已经了解了简单工厂模式,改善了代码,降低了耦合,增加了可扩展性。在本节中,继续学习了另外一种设计模式–策略模式,封装了变化,封装了算法的公共功能。

参考图如下:



参考代码如下:

#-*- coding=UTF-8 -*-
'''
Created on 2015年4月29日

@author: ChangSu
'''

class CashSuper(object):
'''
@summary: 现金收取算法基类
'''
def acceptMCash(self,money):
pass

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

class CashRebate(CashSuper):
#折扣收费
discount=0.0
def __init__(self,ds):
self.discount=ds
def acceptMCash(self, money):
return money*self.discount

class CashReturn(CashSuper):
#返利收费
maxcash=0
returnmoney=0
def __init__(self,mc,rm):
self.maxcash=mc
self.returnmoney=rm
def acceptMCash(self, money):
if money>=self.maxcash:
return money-self.returnmoney
else:
return money

#策略类
class CashContext():
def __init__(self,cs):
self.cs=cs
def GetResult(self,money):
return self.cs.acceptMCash(money)

if __name__=='__main__':
money = input("money:")
strategy={}
strategy[1]=CashContext(CashNormal())
strategy[2]=CashContext(CashRebate(0.8))
strategy[3]=CashContext(CashReturn(300,100))

ctype=input('1~normal,2~0.8 discount,3~(300-100)')
if ctype in strategy:
sg=strategy[ctype]
else:
sg=strategy[1]
print 'you need cash:',sg.GetResult(money)


策略模式与简单工厂模式的区别:

咋一看,感觉策略模式和简单工厂模式很相似。比较容易弄混,以下给出个人的一点小小理解(初学勿喷~~):

1、【简单工厂设计模式】: 通过 工厂类 返回用户需要的算法类对象,在工厂类中创建好对象,返回给用户,用户再调用该对象的方法。

【策略模式】:用户创建好已有的对象,并传递给策略类,在策略类中调用该方法,将该算法类对象的方法封装在同一个策略类方法中。用户只需要访问该策略类方法即可,不会知道里面具体如何实现,调用哪些方法。

2、另一方面,策略模式 用户调用的是自己创建的对象,而非工厂类已经初始定义好的对象。这样一来,用户只需要增加一个新类,创建对象,传递即可,而不用修改策略类。

简单工厂模式和策略模式的结合

但是,在策略模式中,客户端需要需要通过条件选择,来选择用户需要的算法类,并创建对象。那么是否可以将选择转移离开客户端呢?那么可以将选择转移到 策略类 CashContext类中。如下代码所示:

class CashContext():
def __init__(self,ctype):
strategy={}
strategy[1]=CashNormal()
strategy[2]=CashRebate(0.8)
strategy[3]=CashReturn(300,100)

if ctype in strategy:
self.cs=strategy[ctype]
else:
self.cs=strategy[1]

def GetResult(self,money):
return self.cs.acceptMCash(money)

if __name__=='__main__':
money = input("money:")
ctype=input('1~normal,2~0.8 discount,3~(300-100)')
sg=CashContext(ctype)
print 'you need cash:',sg.GetResult(money)


但是这样又存在一个问题,如果添加一个新的算法类,仍旧需要重新修改策略类,解决的办法是通过 ‘反射’机制来实现。反射机制需要后续继续学习。

参考文献

[1] Cyberspace_TechNode http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

[2] 大话设计模式 程杰 著

[3] 浪天涯 策略模式与简单工厂模式区别(转) http://www.cnblogs.com/langtianya/archive/2013/03/09/2951005.html

[4] 浪天涯 简单工厂模式和策略模式的区别(原)

http://www.cnblogs.com/langtianya/archive/2013/03/08/2950934.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息