虽然设计模式与语言无关,但这并不意味着每一个模式都能在每一门语言中使用。《设计模式:可复用面向对象软件的基础》一书中有 23 个模式,其中有 16 个在动态语言中“不见了,或者简化了”。

1、策略模式概述

策略模式:定义一系列算法,把它们一一封装起来,并且使它们之间可以相互替换。此模式让算法的变化不会影响到使用算法的客户。

电商领域有个使用“策略”模式的经典案例,即根据客户的属性或订单中的商品计算折扣。

假如一个网店制定了下述折扣规则。

有 1000 或以上积分的顾客,每个订单享 5% 折扣。

同一订单中,单个商品的数量达到 20 个或以上,享 10% 折扣。

订单中的不同商品达到 10 个或以上,享 7% 折扣。

简单起见,我们假定一个订单一次只能享用一个折扣。

UML类图如下:

Promotion 抽象类提供了不同算法的公共接口,fidelityPromo、BulkPromo 和 LargeOrderPromo 三个子类实现具体的“策略”,具体策略由上下文类的客户选择。

在这个示例中,实例化订单(Order 类)之前,系统会以某种方式选择一种促销折扣策略,然后把它传给 Order 构造方法。具体怎么选择策略,不在这个模式的职责范围内。(选择策略可以使用工厂模式。)

2、传统方法实现策略模式:

from abc import ABC, abstractmethod

from collections import namedtuple

Customer = namedtuple('Customer', 'name fidelity')

class LineItem:

"""订单中单个商品的数量和单价"""

def __init__(self, product, quantity, price):

self.product = product

self.quantity = quantity

self.price = price

def total(self):

return self.price * self.quantity

class Order:

"""订单"""

def __init__(self, customer, cart, promotion=None):

self.customer = customer

self.cart = list(cart)

self.promotion = promotion

def total(self):

if not hasattr(self, '__total'):

self.__total = sum(item.total() for item in self.cart)

return self.__total

def due(self):

if self.promotion is None:

discount = 0

else:

discount = self.promotion.discount(self)

return self.total() - discount

def __repr__(self):

fmt = ''

return fmt.format(self.total(), self.due())

class Promotion(ABC): # 策略:抽象基类

@abstractmethod

def discount(self, order):

"""返回折扣金额(正值)"""

class FidelityPromo(Promotion): # 第一个具体策略

"""为积分为1000或以上的顾客提供5%折扣"""

def discount(self, order):

return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0

class BulkItemPromo(Promotion): # 第二个具体策略

"""单个商品为20个或以上时提供10%折扣"""

def discount(self, order):

discount = 0

for item in order.cart:

if item.quantity >= 20:

discount += item.total() * 0.1

return discount

class LargeOrderPromo(Promotion): # 第三个具体策略

"""订单中的不同商品达到10个或以上时提供7%折扣"""

def discount(self, order):

distinct_items = {item.product for item in order.cart}

if len(distinct_items) >= 10:

return order.total() * 0.07

return 0

joe = Customer('John Doe', 0)

ann = Customer('Ann Smith', 1100)

cart = [LineItem('banana', 4, 0.5),

LineItem('apple', 10, 1.5),

LineItem('watermellon', 5, 5.0)]

print('策略一:为积分为1000或以上的顾客提供5%折扣')

print(Order(joe, cart, FidelityPromo()))

print(Order(ann, cart, FidelityPromo()))

banana_cart = [LineItem('banana', 30, 0.5),

LineItem('apple', 10, 1.5)]

print('策略二:单个商品为20个或以上时提供10%折扣')

print(Order(joe, banana_cart, BulkItemPromo()))

long_order = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]

print('策略三:订单中的不同商品达到10个或以上时提供7%折扣')

print(Order(joe, long_order, LargeOrderPromo()))

print(Order(joe, cart, LargeOrderPromo()))

输出:

策略一:为积分为1000或以上的顾客提供5%折扣

策略二:单个商品为20个或以上时提供10%折扣

策略三:订单中的不同商品达到10个或以上时提供7%折扣

3、使用函数实现策略模式

在传统策略模式中,每个具体策略都是一个类,而且都只定义了一个方法,除此之外没有其他任何实例属性。它们看起来像是普通的函数一样。的确如此,在 Python 中,我们可以把具体策略换成了简单的函数,并且去掉策略的抽象类。

from collections import namedtuple

Customer = namedtuple('Customer', 'name fidelity')

class LineItem:

def __init__(self, product, quantity, price):

self.product = product

self.quantity = quantity

self.price = price

def total(self):

return self.price * self.quantity

class Order:

def __init__(self, customer, cart, promotion=None):

self.customer = customer

self.cart = list(cart)

self.promotion = promotion

def total(self):

if not hasattr(self, '__total'):

self.__total = sum(item.total() for item in self.cart)

return self.__total

def due(self):

if self.promotion is None:

discount = 0

else:

discount = self.promotion(self)

return self.total() - discount

def __repr__(self):

fmt = ''

return fmt.format(self.total(), self.due())

def fidelity_promo(order):

"""为积分为1000或以上的顾客提供5%折扣"""

return order.total() * .05 if order.customer.fidelity >= 1000 else 0

def bulk_item_promo(order):

"""单个商品为20个或以上时提供10%折扣"""

discount = 0

for item in order.cart:

if item.quantity >= 20:

discount += item.total() * .1

return discount

def large_order_promo(order):

"""订单中的不同商品达到10个或以上时提供7%折扣"""

distinct_items = {item.product for item in order.cart}

if len(distinct_items) >= 10:

return order.total() * .07

return 0

joe = Customer('John Doe', 0)

ann = Customer('Ann Smith', 1100)

cart = [LineItem('banana', 4, 0.5),

LineItem('apple', 10, 1.5),

LineItem('watermellon', 5, 5.0)]

print('策略一:为积分为1000或以上的顾客提供5%折扣')

print(Order(joe, cart, fidelity_promo))

print(Order(ann, cart, fidelity_promo))

banana_cart = [LineItem('banana', 30, 0.5),

LineItem('apple', 10, 1.5)]

print('策略二:单个商品为20个或以上时提供10%折扣')

print(Order(joe, banana_cart, bulk_item_promo))

long_order = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]

print('策略三:订单中的不同商品达到10个或以上时提供7%折扣')

print(Order(joe, long_order, large_order_promo))

print(Order(joe, cart, large_order_promo))

其实只要是支持高阶函数的语言,就可以如此实现,例如 C# 中,可以用委托实现。只是如此实现反而使代码变得复杂不易懂。而 Python 中,函数天然就可以当做参数来传递。

值得注意的是,《设计模式:可复用面向对象软件的基础》一书的作者指出:“策略对象通常是很好的享元。” 享元是可共享的对象,可以同时在多个上下文中使用。共享是推荐的做法,这样不必在每个新的上下文(这里是 Order 实例)中使用相同的策略时不断新建具体策略对象,从而减少消耗。因此,为了避免 [策略模式] 的运行时消耗,可以配合 [享元模式] 一起使用,但这样,代码行数和维护成本会不断攀升。

在复杂的情况下,需要具体策略维护内部状态时,可能需要把“策略”和“享元”模式结合起来。但是,具体策略一般没有内部状态,只是处理上下文中的数据。此时,一定要使用普通的函数,别去编写只有一个方法的类,再去实现另一个类声明的单函数接口。函数比用户定义的类的实例轻量,而且无需使用“享元”模式,因为各个策略函数在 Python 编译模块时只会创建一次。普通的函数也是“可共享的对象,可以同时在多个上下文中使用”。

以上就是详解Python设计模式之策略模式的详细内容,更多关于Python 策略模式的资料请关注我们其它相关文章!

本文标题: 详解Python设计模式之策略模式

本文地址: http://www.cppcns.com/jiaoben/python/319771.html

python策略模式包含角色_详解Python设计模式之策略模式相关推荐

  1. python中break怎么用_详解Python中break语句的用法

    详解Python中break语句的用法 在Python中的break语句终止当前循环,继续执行下一个语句,就像C语言中的break一样. break最常见的用途是当一些外部条件被触发,需要从一个循环中 ...

  2. 用于生成随机数的python标准库模块是_详解Python基础random模块随机数的生成

    详解Python基础random模块随机数的生成 来源:中文源码网    浏览: 次    日期:2019年11月5日 [下载文档:  详解Python基础random模块随机数的生成.txt ] ( ...

  3. [转载] python中for语句用法_详解Python中for循环的使用_python

    参考链接: 在Python中将else条件语句与for循环一起使用 这篇文章主要介绍了Python中for循环的使用,来自于IBM官方网站技术文档,需要的朋友可以参考下 for 循环 本系列前面 &q ...

  4. python壁纸高清图片_详解Python静态网页爬取获取高清壁纸

    前言 在设计爬虫项目的时候,首先要在脑内明确人工浏览页面获得图片时的步骤 一般地,我们去网上批量打开壁纸的时候一般操作如下: 1.打开壁纸网页 2.单击壁纸图(打开指定壁纸的页面) 3.选择分辨率(我 ...

  5. python中for语句用法_详解Python中for循环的使用_python

    这篇文章主要介绍了Python中for循环的使用,来自于IBM官方网站技术文档,需要的朋友可以参考下 for 循环 本系列前面 "探索 Python,第 5 部分:用 Python 编程&q ...

  6. python怎么设置七牛云_详解Python在七牛云平台的应用(一)

    七牛云七牛云是国内领先的企业级云服务商.专注于以数据为核心的云计算业务,围绕富媒体场景推出了对象存储.融合CDN.容器云.大数据.深度学习平台等产品,并提供一站式视频云解决方案,同时打造简单,可信赖的 ...

  7. python手机壁纸超清_详解Python静态网页爬取获取高清壁纸

    前言 在设计爬虫项目的时候,首先要在脑内明确人工浏览页面获得图片时的步骤 一般地,我们去网上批量打开壁纸的时候一般操作如下: 1.打开壁纸网页 2.单击壁纸图(打开指定壁纸的页面) 3.选择分辨率(我 ...

  8. python可以播放音乐吗_详解python播放音频的三种方法

    第一种 使用pygame模块 pygame.mixer.init() pygame.mixer.music.load(self.wav_file) pygame.mixer.music.set_vol ...

  9. python命令提示符窗口在哪里_详解python命令提示符窗口下如何运行python脚本

    以arcgispro的python脚本为例在arcgispro自带的python窗口下运行python脚本 需求: 将arcgispro的.aprx项目包中gdb的数据源路径更换为sde数据源路径. ...

最新文章

  1. 受用一生的高效 PyCharm 使用技巧(一)
  2. iPhone清理喇叭灰尘_手机喇叭孔灰尘清理
  3. verilog基础—规范化参数定义parameter
  4. vector 声明固定长度的数组
  5. Microsoft Office企业项目管理(EPM)解决方案
  6. leetcode 802. Find Eventual Safe States | 802. 找到最终的安全状态(有向图DFS)
  7. ubuntu编译内核_鸿蒙源码下载并编译
  8. Java简单验证码的识别
  9. 任正非:5G也不是万能的,发展也需要一个过程
  10. 腾讯云window阿帕奇服务器开通ssl证书实现https访问
  11. Twitterrific for Mac(Twitter客户端)
  12. 【TFT屏幕】1.44寸彩屏
  13. 嵌入式开发笔记——调试组件SEGGER_RTT
  14. layui内置模块(element常用元素操作)
  15. Debian11(Bullseye)系统安装docker及启动失败问题解决
  16. WKWebView 白屏问题
  17. VS Code配置用批处理编译C++
  18. 项目三《小米官网仿写》
  19. EtherCAT主站SOEM在TI AM335x上的移植
  20. 【算法反刍】递归与递推

热门文章

  1. RTP格式图 NNEXB格式和RTP格式
  2. FreeSql (二十九)Lambda 表达式
  3. 记录知识点或技术方案信息
  4. 《PWA实战:面向下一代的Progressive Web APP》读书笔记
  5. 京东购物在微信等场景下的算法应用实践
  6. 聊聊毕业设计系列 --- 系统实现
  7. 从Java到Go面向对象--继承思想.md
  8. Kali-linux使用Nessus
  9. datetime-时间日期模块
  10. 2018-2019-1 《信息安全系统设计基础》教学进程