这一节,我们使用python的策略模式进行一个简单的打折相关的设计开发(这里参考了-大话设计模式一书,有时间的同学可以看看,非常不错的一本书),我们的需求是什么呢?超市进行销售商品,一般有几种类型的销售模式:
- 原价销售,无折扣
- 直接折扣销售,比如打五折
- 满几送几的销售
还有很多别的这里就不举例了,自己可以根据情况发挥。
首先我们要想到的是将里面的内容进行抽象,这里怎么抽象?这里最重要的就是如何打折了,那么我们就先抽取一个打折类的基类。
其次,这里的三种折扣策略就是打折基类的实现喽。
再次,我们还要考虑怎么去实例化这三个子类,这里就是用我们上节用到的工厂模式,根据不同参数生成不同的实例,这样也不错。
那么最后,我们要考虑的就是如何分离显示和逻辑的接口,这就要再加一层(记得某个牛逼软件人物说过,加一层结构是万能解决方式,哈哈,不过加多了应该不好,慢慢理解。),我们这里再加一层上下文管理(就是起个名字而已,没啥特殊还以,只是可以连接显示和逻辑层。。。。)
现在我们来进行代码实现:
# coding=utf8
# 抽象基类
class CashSuper(object):
def __init__(self):
pass
def get_result(self):
pass
# 不打折的子类
class NormalCash(CashSuper):
def __init__(self, money):
super(NormalCash, self).__init__()
self.money = money
def get_result(self):
return self.money
# 折扣子类
class ReboteCash(CashSuper):
def __init__(self, money, rebote):
super(ReboteCash, self).__init__()
self.money = money
self.rebote = rebote
def get_result(self):
return self.money * self.rebote
# 满几送几子类
class ReturnCash(CashSuper):
def __init__(self, money, m_condition, m_return):
super(ReturnCash, self).__init__()
self.money = money
self.m_condition = m_condition
self.m_return = m_return
def get_result(self):
if self.money > self.m_condition:
return self.money - self.m_return
else:
return self.money
# 工厂类
class CashFactory:
def __init__(self, cash_type, money):
self.cash_type = cash_type
self.money = money
def return_instance(self):
if self.cash_type == "normal":
return NormalCash(self.money)
# 上下文类
class CashContext:
def __init__(self, cash_type, money):
self.cash_type = cash_type
self.money = money
def get_isntance(self):
return CashFactory(self.cash_type, self.money)
def get_result(self):
factory = self.get_isntance()
cash_instance = factory.return_instance()
return cash_instance.get_result()
if __name__ == '__main__':
cash_context = CashContext("normal", 1000)
print cash_context.get_result()
里面没有完全实现,只是一个实例演示,可以根据自己随意改造。
下节我们准备进行装饰模式的实例讲解,学过python的同学对这个肯定一点也不陌生。