经典的策略模式案例

问题描述

使用“策略”设计模式处理订单折扣的 UML 类图

定义一系列算法,把它们一一封装起来,并且使它们可以相互替换。本模式使得算法可以独立于使用它的客户而变化。

电商领域有个功能明显可以使用“策略”模式,即根据客户的属性或订单中的商品计算折扣。

假如一个网店制定了下述折扣规则,每个订单只能享用一个折扣:

  1. Customers with 1,000 or more fidelity points get a global 5% discount per order.
  2. A 10% discount is applied to each line item with 20 or more units in the same order.
  3. Orders with at least 10 distinct items get a 7% global discount.

content

把一些计算委托给实现不同算法的可互换组件,它提供服务。在这个电商示例中,上下文是 Order,它会根据不同的算法计算促销折扣。

strategy

实现不同算法的组件共同的接口。在这个示例中,名为 Promotion 的抽象类扮演这个角色。

concrete strategy

“策略”的具体子类。fidelityPromo、BulkPromo 和 LargeOrderPromo 是这里实现的三个具体策略。

问题解决代码

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 = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
#--------------------------------------------------------
class Promotion(ABC): # the Strategy: an abstract base class
@abstractmethod
def discount(self, order):
"""Return discount as a positive dollar amount"""
#--------------------------------------------------------
class FidelityPromo(Promotion): # first Concrete Strategy
"""5% discount for customers with 1000 or more fidelity points"""
def discount(self, order):
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
#--------------------------------------------------------
class BulkItemPromo(Promotion): # second Concrete Strategy
"""10% discount for each LineItem with 20 or more units"""
def discount(self, order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
#--------------------------------------------------------
class LargeOrderPromo(Promotion): # third Concrete Strategy
"""7% discount for orders with 10 or more distinct items"""
def discount(self, order):
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
# 两个顾客:joe 的积分是 0,ann 的积分是 1100。
joe = Customer('John Doe', 0)
ann = Customer('Ann Smith', 1100)
# 有三个商品的购物车
cart = [LineItem('banana', 4, .5),
LineItem('apple', 10, 1.5),
LineItem('watermellon', 5, 5.0)]
# fidelityPromo 没给 joe 提供折扣
Order(joe, cart, FidelityPromo())
<Order total: 42.00 due: 42.00>
# ann 得到了 5% 折扣,因为她的积分超过 1000
Order(ann, cart, FidelityPromo())
<Order total: 42.00 due: 39.90>
# banana_cart 中有 30 把香蕉和 10 个苹果
banana_cart = [LineItem('banana', 30, .5),
LineItem('apple', 10, 1.5)]
# BulkItemPromo 为 joe 购买的香蕉优惠了 1.50 美元
Order(joe, banana_cart, BulkItemPromo())
<Order total: 30.00 due: 28.50>
# long_order 中有 10 个不同的商品,每个商品的价格为 1.00 美元
long_order = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]
# LargerOrderPromo 为 joe 的整个订单提供了 7% 折扣
Order(joe, long_order, LargeOrderPromo())
<Order total: 10.00 due: 9.30>
Order(joe, cart, LargeOrderPromo())
<Order total: 42.00 due: 42.00>

案例来自《Fluent Python》Luciano Ramalho著

Python3面向对象——案例-01的更多相关文章

  1. python 面向对象编程案例01

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #面向对象编程案例01 class Behave(): def __init__(self,name): se ...

  2. java基础学习05(面向对象基础01)

    面向对象基础01 1.理解面向对象的概念 2.掌握类与对象的概念3.掌握类的封装性4.掌握类构造方法的使用 实现的目标 1.类与对象的关系.定义.使用 2.对象的创建格式,可以创建多个对象3.对象的内 ...

  3. web综合案例01

    web综合案例01 ... .... 内容待添加

  4. python022 Python3 面向对象

    Python3 面向对象 Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对象是很容易的.本章节我们将详细介绍Python的面向对象编程. 如果你以前没有接触 ...

  5. 面向对象案例-学生信息管理系统V0.6

    更新版本 面向对象案例 - 学生信息管理系统V1.0 项目要求: 实体类: 学生类: id, 姓名,年龄,性别,成绩 需要使用数组保存学生信息 Student[] allStu 需要完成的方法 1. ...

  6. 081 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 06 new关键字

    081 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 06 new关键字 本文知识点:new关键字 说明:因为时间紧张,本人写博客过程中只是 ...

  7. 080 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 05 单一职责原则

    080 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 05 单一职责原则 本文知识点:单一职责原则 说明:因为时间紧张,本人写博客过程中只是 ...

  8. 079 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 04 实例化对象

    079 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 04 实例化对象 本文知识点:实例化对象 说明:因为时间紧张,本人写博客过程中只是对知 ...

  9. 078 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 03 创建类

    078 01 Android 零基础入门 02 Java面向对象 01 Java面向对象基础 01 初识面向对象 03 创建类 本文知识点:创建类 说明:因为时间紧张,本人写博客过程中只是对知识点的关 ...

随机推荐

  1. 【转】Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)

    [转]Python之xml文档及配置文件处理(ElementTree模块.ConfigParser模块) 本节内容 前言 XML处理模块 ConfigParser/configparser模块 总结 ...

  2. Getting started with machine learning in Python

    Getting started with machine learning in Python Machine learning is a field that uses algorithms to ...

  3. PCA主成分分析+白化

    参考链接:http://deeplearning.stanford.edu/wiki/index.php/%E4%B8%BB%E6%88%90%E5%88%86%E5%88%86%E6%9E%90 h ...

  4. 七、Sparse Autoencoder介绍

    目前为止,我们已经讨论了神经网络在有监督学习中的应用.在有监督学习中,训练样本是有类别标签的.现在假设我们只有一个没有带类别标签的训练样本集合  ,其中  .自编码神经网络是一种无监督学习算法,它使用 ...

  5. /etc/profile 路径出错后相关的命令失效解决方式

    关于 Linux 的配置文件 /etc/profile 路径出错后相关的命令失效解决方式(如:ls,vi不能用) 今天学习LINUX 下配置jdk 和安装tomcat 通过VI编辑/etc/profi ...

  6. ASP.NET Core Identity 实战(3)认证过程

    如果你没接触过旧版Asp.Net Mvc中的 Authorize 或者 Cookie登陆,那么你一定会疑惑 认证这个名词,这太正式了,这到底代表这什么? 获取资源之前得先过两道关卡Authentica ...

  7. Sql 插入自定义主键

    在遇到数据库设计是自增的主键,且需要插入自定义的主键Id时,这个时候如果直接Insert的话,将会发生错误,错误提示信息: 当 IDENTITY_INSERT 设置为 OFF 时,不能为表 'XXX' ...

  8. 初识numpy

    from numpy import *   导入numpy包 random可以生成随机数组 通过mat函数,将数组转换成矩阵,可以对矩阵进行求逆计算等.其中.I操作实现了矩阵求逆计算操作. 执行矩阵乘 ...

  9. 最全Kafka 设计与原理详解【2017.9全新】

    一.Kafka简介 1.1 背景历史 当今社会各种应用系统诸如商业.社交.搜索.浏览等像信息工厂一样不断的生产出各种信息,在大数据时代,我们面临如下几个挑战: 如何收集这些巨大的信息 如何分析它 如何 ...

  10. node调试工具--nodemon