美文网首页
Python 版的策略模式

Python 版的策略模式

作者: u14e | 来源:发表于2019-06-03 18:06 被阅读0次

应用场景: 电商领域根据客户的属性或订单中的商品计算折扣

折扣规则:

  • 有 1000 或以上积分的顾客,每个订单享 5% 折扣。
  • 同一订单中,单个商品的数量达到 20 个或以上,享 10% 折扣。
  • 订单中的不同商品达到 10 个或以上,享 7% 折扣

假定一个订单一次只能享用一个折扣

1. 面向对象版的策略模式

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 = 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):
    @abstractmethod
    def discount(self, order):
        """Return discount as a positive dollar amount"""


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


def run():
    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)]
    print(Order(joe, cart, FidelityPromo()))
    print(Order(ann, cart, FidelityPromo()))

    banane_cart = [LineItem('banana', 30, .5),
                   LineItem('apple', 10, 1.5)]
    print(Order(joe, banane_cart, BulkItemPromo()))

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


if __name__ == '__main__':
    run()

2. 函数版的策略模式

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 = 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 = '<Order total: {:.2f} due: {:.2f}>'
        return fmt.format(self.total(), self.due())


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


def bulk_item_promo(order):
    discount = 0
    for item in order.cart:
        if item.quantity >= 20:
            discount += item.total() * 0.1
    return discount


def large_order_promo(order):
    distinct_items = {item.product for item in order.cart}
    if len(distinct_items) >= 10:
        return order.total() * 0.07
    return 0


def run():
    print(Order(joe, cart, fidelity_promo))
    print(Order(ann, cart, fidelity_promo))

    print(Order(joe, banane_cart, bulk_item_promo))

    print(Order(joe, long_order, large_order_promo))


if __name__ == '__main__':
    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)]

    banane_cart = [LineItem('banana', 30, .5),
                   LineItem('apple', 10, 1.5)]

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

    run()

计算最优折扣

promos = [fidelity_promo, bulk_item_promo, large_order_promo]

def best_promo(order):
    """选择可用的最佳折扣"""
    return max(promo(order) for promo in promos)

def best_run():
    print(Order(joe, long_order, best_promo))
    print(Order(joe, banane_cart, best_promo))
    print(Order(ann, cart, best_promo))

使用 inspect.getmembers 内省独立模块

import inspect
import promotions

# inspect.getmembers 获取对象(这里是模块)的属性
promos = [func for name, func in
          inspect.getmembers(promotions, inspect.isfunction)]

promotions.py 里面是策略函数:

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


def bulk_item_promo(order):
    discount = 0
    for item in order.cart:
        if item.quantity >= 20:
            discount += item.total() * 0.1
    return discount


def large_order_promo(order):
    distinct_items = {item.product for item in order.cart}
    if len(distinct_items) >= 10:
        return order.total() * 0.07
    return 0

来源: 《流畅的Python》6.1节

相关文章

  • Python 版的策略模式

    应用场景: 电商领域根据客户的属性或订单中的商品计算折扣 折扣规则: 有 1000 或以上积分的顾客,每个订单享 ...

  • 【转】唐奇安、追涨杀跌、动态平衡策略

    增强版唐奇安通道策略 Python版追涨杀跌策略基于 数字货币的动态平衡策略

  • 手把手教你把Python单品种策略改造成多品种策略

    上期文章,实现了一个非常简单的Python策略:「Python版追涨杀跌策略」,该策略可以操作一个账户在某个交易对...

  • Python策略模式

    策略模式,同一问题有多种不同的解法,即不同策略,一个物体可以动态地对策略进行更换。

  • Python策略模式

    [python|高级篇|笔记|设计模式|策略模式] 引子 接着开始吧,还是读了HF之后的学习记录。继承并不是适当的...

  • 基础-单例模式

    单例模式总结-Python实现 面试里每次问设计模式,必问单例模式 来自《Python设计模式》(第2版) 1.理...

  • 策略模式

    设计原则: 策略模式: 如图是一个简化版的策略模式,场景:MallardGame在这里面是一个战士,Mallard...

  • Python 设计模式初探

    Python 设计模式初探 本博客是在阅读精通Python设计模式(中文版),以及阅读 Mask R-CNN 第三...

  • 设计模式(Python)-策略模式

    本系列文章是希望将软件项目中最常见的设计模式用通俗易懂的语言来讲解清楚,并通过Python来实现,每个设计模式都是...

  • Python设计模式 - 策略模式

    """ 策略模式:是一种定义一系列算法的方法,从概念上,所有这些算法完成的都是相同的工作,只是实现不同。 所以可以...

网友评论

      本文标题:Python 版的策略模式

      本文链接:https://www.haomeiwen.com/subject/aakhxctx.html