python: Strategy Pattern

以珠宝为例:

  • 上下文(Context):珠宝(Jewelry),它有基础属性(材质、重量),但定价方式可以灵活变化。
  • 策略接口(Strategy):珠宝定价策略(PricingStrategy),定义统一的定价方法。
  • 具体策略(Concrete Strategy):不同的定价规则(如按重量定价、按工艺复杂度定价、按品牌溢价定价)。
python 复制代码
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:策略模式(Strategy Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/2/24 23:32
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : PricingStrategy.py
from abc import ABC, abstractmethod
 
# --------------------------
# 1. 策略接口:定义定价策略的统一方法
# --------------------------
class PricingStrategy(ABC):
    """
 
    """
    @abstractmethod
    def calculate_price(self, jewelry):
        """
        计算珠宝价格的抽象方法,由具体策略实现
        :param jewelry:
        :return:
        """
        pass
python 复制代码
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:策略模式(Strategy Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/2/24 23:34
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : WeightBasedPricing.py
 
from StrategyPattern.PricingStrategy import PricingStrategy
 
 
# --------------------------
# 2. 具体策略类:不同的定价规则
# --------------------------
 
class WeightBasedPricing(PricingStrategy):
    """
    策略1:按重量定价(黄金、白银等贵金属常用)
    """
    def calculate_price(self, jewelry)->float:
        """
        基础单价 * 重量(克)
        :param jewelry:
        :return:
        """
        unit_price = {"gold": 600, "silver": 8, "platinum": 300}[jewelry.material]
        return unit_price * jewelry.weight
 
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:策略模式(Strategy Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/2/24 23:35
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : CraftComplexityPricing.py
 
from StrategyPattern.PricingStrategy import PricingStrategy
 
 
# --------------------------
# 2. 具体策略类:不同的定价规则
# --------------------------
 
class CraftComplexityPricing(PricingStrategy):
    """
     策略2:按工艺复杂度定价(钻石、手工饰品常用)
    """
    def calculate_price(self, jewelry)->float:
        """
        基础价 + 复杂度系数 * 工艺费
        :param jewelry:
        :return:
        """
        base_price = 1000
        complexity_factor = {"simple": 1, "medium": 2, "complex": 3}[jewelry.craft_complexity]
        return base_price * complexity_factor
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:策略模式(Strategy Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/2/24 23:36
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : BrandPremiumPricing.py
from StrategyPattern.PricingStrategy import PricingStrategy
 
 
# --------------------------
# 2. 具体策略类:不同的定价规则
# --------------------------
 
 
class BrandPremiumPricing(PricingStrategy):
    """
    策略3:按品牌溢价定价(奢侈品珠宝常用)
    """
    def calculate_price(self, jewelry)->float:
        """
        基础价 * 品牌溢价系数
        :param jewelry:
        :return:
        """
        base_price = jewelry.base_price
        brand_factor = {"cartier": 5, "tiffany": 4, "local": 1.2}[jewelry.brand]
        return base_price * brand_factor
python 复制代码
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:策略模式(Strategy Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/2/24 23:38
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : Jewelry.py
 
 
# --------------------------
# 3. 上下文类:珠宝(使用策略的主体)
# --------------------------
class Jewelry:
    """
 
    """
    def __init__(self, name, material=None, weight=None, craft_complexity=None, brand=None, base_price=None):
        """
 
        :param name:
        :param material:
        :param weight:
        :param craft_complexity:
        :param brand:
        :param base_price:
        """
        self.name = name          # 珠宝名称
        self.material = material  # 材质(黄金/白银/铂金)
        self.weight = weight      # 重量(克)
        self.craft_complexity = craft_complexity  # 工艺复杂度
        self.brand = brand        # 品牌
        self.base_price = base_price  # 品牌珠宝基础价
        self.pricing_strategy = None  # 定价策略(初始为空)
 
 
    def set_pricing_strategy(self, strategy)->None:
        """
        设置定价策略(核心:动态替换策略)
        :param strategy:
        :return:
        """
        self.pricing_strategy = strategy
 
 
    def get_price(self)->float:
        """
        计算价格(委托给策略类)
        :return:
        """
        if not self.pricing_strategy:
            raise ValueError("未设置定价策略!")
        return self.pricing_strategy.calculate_price(self)
python 复制代码
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:策略模式(Strategy Pattern)
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/2/24 23:41
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : StrategyBll.py
 
from StrategyPattern.Jewelry import Jewelry
from StrategyPattern.WeightBasedPricing import WeightBasedPricing
from StrategyPattern.BrandPremiumPricing import BrandPremiumPricing
from StrategyPattern.CraftComplexityPricing import CraftComplexityPricing
 
 
 
 
class StrategyBll(object):
    """
 
    """
    def demo(self):
        """
 
        :return:
        """
        # 示例1:黄金项链(按重量定价)
        gold_necklace = Jewelry(
            name="黄金项链",
            material="gold",
            weight=10  # 10克
        )
        gold_necklace.set_pricing_strategy(WeightBasedPricing())
        print(f"{gold_necklace.name} 价格:{gold_necklace.get_price()} 元")  # 600*10=6000元
 
        # 示例2:手工钻石戒指(按工艺复杂度定价)
        diamond_ring = Jewelry(
            name="手工钻石戒指",
            craft_complexity="complex"
        )
        diamond_ring.set_pricing_strategy(CraftComplexityPricing())
        print(f"{diamond_ring.name} 价格:{diamond_ring.get_price()} 元")  # 1000*3=3000元
 
        # 示例3:卡地亚手镯(按品牌溢价定价)
        cartier_bangle = Jewelry(
            name="卡地亚手镯",
            brand="cartier",
            base_price=2000
        )
        cartier_bangle.set_pricing_strategy(BrandPremiumPricing())
        print(f"{cartier_bangle.name} 价格:{cartier_bangle.get_price()} 元")  # 2000*5=10000元
 
        # 动态切换策略:比如卡地亚手镯临时按重量定价(假设补充材质/重量)
        cartier_bangle.material = "platinum"
        cartier_bangle.weight = 5
        cartier_bangle.set_pricing_strategy(WeightBasedPricing())
        print(f"切换策略后,{cartier_bangle.name} 价格:{cartier_bangle.get_price()} 元")  # 300*5=1500元

调用:

python 复制代码
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  oracle 21c Neo4j
# Datetime  : 2026/2/18 20:58
# User      : geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : main.py
# explain   : 学习
from bll.MementoBll import MementoBll
from bll.CommandBll import CommandBll
from bll.StateBll import StateBll
from bll.TemplateMethodBll import TemplateMethodBll
from bll.VisitorBll import VisitorBll
from bll.StrategyBll import StrategyBll
 
if __name__ == '__main__':
 
    #实现备忘录模式(Memento Pattern)
    #mementobll= MementoBll()
    #mementobll.demo()
    #命令模式(Command Pattern)
    #commandBll= CommandBll()
    #commandBll.demo()
    # 状态模式 State Pattern
    #stateBll =StateBll()
    #stateBll.demo()
    # 模板方法模式 Template Method Pattern
    #templateMethodBll= TemplateMethodBll()
    #templateMethodBll.demo()
    # 访问者模式(Visitor Pattern)
    #visitor = VisitorBll()
    #visitor.demo()
    # 策略模式(Strategy Pattern)
    strategyBll = StrategyBll()
    strategyBll.demo()
 
 
    print('hi,welcome geovindu.')

输出:

相关推荐
逸A16 分钟前
携程app逆向那些事(ai agent能力偏弱时)
人工智能·python·安全
silvamux_27 分钟前
OpenAI Python SDK v1 迁移实战
开发语言·python
旋生万物27 分钟前
螺旋数不是玄学:Python 实现广义复数与等角螺线
开发语言·人工智能·python·云原生·aigc·软件工程·后端开发
小小程序猴139 分钟前
用工程视角建模企业AI培训周期:三段账本估算器(Python实现)
开发语言·人工智能·python
happy_baymax40 分钟前
Dell G3 3590 黑苹果实战:OpenCore 1.0.8 + NullMoth 驱动让 GTX 1660 跑起 Metal
策略模式
十二同学啊1 小时前
Python FastAPI 项目使用 Docker 部署并映射端口(完整教程)
python·docker·fastapi
不爱吃鱼的蔓热莓1 小时前
Autosar arxml异常字符串处理
python
FBI HackerHarry浩1 小时前
Pytorch中 CPU tensor vs GPU tensor
人工智能·pytorch·python·深度学习
wewowilling1 小时前
工作流 .... coze平台--AI--Agent--RAG--Function Calling
python·低代码·agent·零代码·工作流·coze
小草cys1 小时前
图片一键转全矢量可编辑PPT——纯Python实现,零依赖,离线可用
人工智能·python·powerpoint