Python设计模式之策略模式实例详解

yipeiwu_com6年前Python基础

本文实例讲述了Python设计模式之策略模式。分享给大家供大家参考,具体如下:

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

下面是一个商场活动的实现

#!/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)

运行结果:

原价: 500
选择折扣方式: 1) 原价 2) 8折 3) 满100减10: 2
需要支付:  400.0

这几个类的设计如下图:

使用一个策略类CashSuper定义需要的算法的公共接口,定义三个具体策略类:CashNormal,CashRebate,CashReturn,继承于CashSuper,定义一个上下文管理类,接收一个策略,并根据该策略得出结论,当需要更改策略时,只需要在实例的时候传入不同的策略就可以,免去了修改类的麻烦

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python的id()函数解密过程

>>> a = 2.5 >>> b = 2.5 >>> c = b >>> a is c False >&g...

Python collections模块使用方法详解

Python collections模块使用方法详解

一、collections模块 1.函数namedtuple (1)作用:tuple类型,是一个可命名的tuple (2)格式:collections(列表名称,列表) (3)̴...

python获取远程图片大小和尺寸的方法

本文实例讲述了python获取远程图片大小和尺寸的方法。分享给大家供大家参考。具体分析如下: 这段代码通过urllib2打开远程图片,通过cStringIO读取文件内容,不用保存到磁盘即...

详解python tkinter教程-事件绑定

一个Tkinter主要跑在mainloop进程里。Events可能来自多个地方,比如按键,鼠标,或是系统事件。 Tkinter提供了丰富的方法来处理这些事件。对于每一个控件Widge...

python3.6的venv模块使用详解

python3.6的venv模块使用详解

今天,在在使用 pycharm 的使用,进行创建 python的时候,发现使用默认的创建的选项使用的python 3环境 。而我系统默认的python环境是 python 2.7 环境;...