首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python: Decorator Pattern

python: Decorator Pattern

作者头像
geovindu
发布2026-06-18 19:39:13
发布2026-06-18 19:39:13
300
举报

把「珠宝实体属性」(如材质、镶嵌、工艺)和「业务流程」(如加工、质检、证书、包装)结合起来 —— 基础珠宝有核心属性和基础加工流程,通过装饰器既可以为珠宝添加增值属性,也可以为其加工流程添加增值环节,最终形成 “珠宝产品 + 全流程服务” 的完整解决方案。

代码语言:javascript
复制
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:装饰器模式(Decorator 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/3/7 14:21
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : JewelryProduct.py
from abc import ABC, abstractmethod
 
 
# ===================== 1. 抽象组件:珠宝产品+流程接口 =====================
class JewelryProduct(ABC):
    """
    珠宝产品抽象类:整合实体属性(价格、描述)和业务流程(加工)
    """
    # ---- 实体属性相关 ----
    @abstractmethod
    def get_price(self) -> float:
        """
        获取珠宝总价
        :return:
        """
        pass
 
    @abstractmethod
    def get_description(self) -> str:
        """
        获取珠宝完整描述
        :return:
        """
        pass
 
    # ---- 业务流程相关 ----
    @abstractmethod
    def process(self) -> list[str]:
        """
        执行珠宝加工流程,返回流程步骤列表
        :return:
        """
        pass
代码语言:javascript
复制
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:装饰器模式(Decorator 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/3/7 14:22
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : PlainGoldRing.py
 
import time
from DecoratorPattern.JewelryProduct import JewelryProduct
 
 
# ===================== 2. 具体组件:基础珠宝(素金戒指) =====================
class PlainGoldRing(JewelryProduct):
    """
    基础产品:素金戒指(无装饰,仅基础加工流程)
    """
 
    def __init__(self, weight: float = 5.0):
        """
 
        :param weight:
        """
        # 实体属性
        self.weight = weight  # 重量(克)
        self.base_price = weight * 500  # 基础价:500元/克(足金)
        self.desc = f"{weight}克素金戒指(999足金)"
 
        # 业务流程
        self.process_steps = []  # 加工步骤记录
 
    # ---- 实体属性实现 ----
    def get_price(self) -> float:
        """
 
        :return:
        """
        return self.base_price
 
    def get_description(self) -> str:
        """
 
        :return:
        """
        return self.desc
 
    # ---- 业务流程实现 ----
    def process(self) -> list[str]:
        """
        基础加工流程:制坯 → 打磨
        :return:
        """
        print(f"\n=== 开始加工【{self.get_description()}】===")
        # 步骤1:制作毛坯
        time.sleep(0.5)
        self.process_steps.append("制作黄金毛坯")
        print(f"✅ 完成:{self.process_steps[-1]}")
 
        # 步骤2:基础打磨
        time.sleep(0.5)
        self.process_steps.append("基础打磨抛光")
        print(f"✅ 完成:{self.process_steps[-1]}")
 
        return self.process_steps
代码语言:javascript
复制
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:装饰器模式(Decorator 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/3/7 14:24
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : JewelryDecorator.py
from abc import ABC, abstractmethod
from DecoratorPattern.JewelryProduct import JewelryProduct
 
 
# ===================== 3. 装饰器抽象类:统一扩展属性+流程 =====================
class JewelryDecorator(JewelryProduct):
    """
    珠宝装饰器基类:同时支持扩展属性和流程
    """
    def __init__(self, jewelry: JewelryProduct):
        """
 
        :param jewelry:
        """
        self.jewelry = jewelry  # 被装饰的珠宝对象
 
    # 所有方法都需抽象,由具体装饰器实现
    @abstractmethod
    def get_price(self) -> float:
        """
        价格
        :return:
        """
        pass
 
    @abstractmethod
    def get_description(self) -> str:
        """
        描述
        :return:
        """
        pass
 
    @abstractmethod
    def process(self) -> list[str]:
        """
        流程
        :return:
        """
        pass
代码语言:javascript
复制
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:装饰器模式(Decorator 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/3/7 14:25
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : DiamondInlayDecorator.py
from DecoratorPattern.JewelryDecorator import JewelryDecorator
from DecoratorPattern.JewelryProduct import JewelryProduct
 
 
# ===================== 4. 具体装饰器:属性扩展(实体特征) =====================
class DiamondInlayDecorator(JewelryDecorator):
    """
    属性装饰器:镶嵌钻石(增加实体属性,更新价格/描述)
    """
    def __init__(self, jewelry: JewelryProduct, diamond_carat: float = 0.3):
        """
 
        :param jewelry:
        :param diamond_carat:
        """
        super().__init__(jewelry)
        self.diamond_carat = diamond_carat
        self.diamond_price = diamond_carat * 8000  # 钻石加价:8000元/克拉
 
 
    def get_price(self) -> float:
        """
        扩展价格:基础价 + 钻石价
        :return:
        """
        return self.jewelry.get_price() + self.diamond_price
 
 
    def get_description(self) -> str:
        """
        扩展描述:基础描述 + 钻石镶嵌信息
        :return:
        """
        return f"{self.jewelry.get_description()},镶嵌{self.diamond_carat}克拉副钻(SI1净度)"
 
 
    def process(self) -> list[str]:
        """
        流程复用基础流程(仅扩展属性,不修改流程)
        :return:
        """
        return self.jewelry.process()
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:装饰器模式(Decorator 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/3/7 14:27
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : EngravingDecorator.py
from DecoratorPattern.JewelryDecorator import JewelryDecorator
from DecoratorPattern.JewelryProduct import JewelryProduct
 
 
# ===================== 4. 具体装饰器:属性扩展(实体特征) =====================
 
class EngravingDecorator(JewelryDecorator):
    """
    属性装饰器:雕花工艺(增加实体属性,更新价格/描述)
    """
    def __init__(self, jewelry: JewelryProduct, pattern: str = "玫瑰花纹"):
        """
 
        :param jewelry:
        :param pattern:
        """
        super().__init__(jewelry)
        self.pattern = pattern
        self.engraving_price = 500  # 雕花工艺加价
 
    def get_price(self) -> float:
        """
 
        :return:
        """
        return self.jewelry.get_price() + self.engraving_price
 
    def get_description(self) -> str:
        """
 
        :return:
        """
        return f"{self.jewelry.get_description()},表面雕刻{self.pattern}"
 
 
    def process(self) -> list[str]:
        """
        流程复用基础流程
        :return:
        """
        return self.jewelry.process()
代码语言:javascript
复制
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:装饰器模式(Decorator 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/3/7 14:29
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : QualityCheckDecorator.py
from DecoratorPattern.JewelryDecorator import JewelryDecorator
from DecoratorPattern.JewelryProduct import JewelryProduct
import time
 
# ===================== 5. 具体装饰器:流程扩展(业务环节) =====================
class QualityCheckDecorator(JewelryDecorator):
    """
    流程装饰器:质检环节(扩展加工流程,不修改实体属性)
    """
 
    def __init__(self, jewelry: JewelryProduct):
        """
 
        :param jewelry:
        """
        super().__init__(jewelry)
        self.check_fee = 200  # 质检服务费
 
 
    def get_price(self) -> float:
        """
        价格:基础价 + 质检费
        :return:
        """
        return self.jewelry.get_price() + self.check_fee
 
 
    def get_description(self) -> str:
        """
        描述:基础描述 + 质检服务
        :return:
        """
        return f"{self.jewelry.get_description()}(含专业质检)"
 
 
    def process(self) -> list[str]:
        """
        流程:基础流程 + 质检步骤
        :return:
        """
        # 先执行原有流程
        steps = self.jewelry.process()
 
        # 追加质检步骤
        time.sleep(0.5)
        steps.append("专业质检(尺寸/纯度/钻石镶嵌牢固度)")
        print(f"✅ 完成:{steps[-1]}")
 
        return steps
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:装饰器模式(Decorator 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/3/7 14:33
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : LuxuryPackagingDecorator.py
from DecoratorPattern.JewelryDecorator import JewelryDecorator
from DecoratorPattern.JewelryProduct import JewelryProduct
import time
 
# ===================== 5. 具体装饰器:流程扩展(业务环节) =====================
class LuxuryPackagingDecorator(JewelryDecorator):
    """
    流程装饰器:高端包装(扩展加工流程)
    """
 
    def __init__(self, jewelry: JewelryProduct, package_type: str = "实木礼盒"):
        """
 
        :param jewelry:
        :param package_type:
        """
        super().__init__(jewelry)
        self.package_type = package_type
        self.package_fee = 150  # 包装服务费
 
    def get_price(self) -> float:
        """
        价格
        :return:
        """
        return self.jewelry.get_price() + self.package_fee
 
    def get_description(self) -> str:
        """
        描述
        :return:
        """
 
        return f"{self.jewelry.get_description()}(含{self.package_type}包装)"
 
    def process(self) -> list[str]:
        """
        流程
        :return:
        """
 
        steps = self.jewelry.process()
 
        # 追加包装步骤
        time.sleep(0.5)
        steps.append(f"高端包装({self.package_type}+绒布内衬)")
        print(f"✅ 完成:{steps[-1]}")
 
        return steps
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:装饰器模式(Decorator 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/3/7 14:31
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : CertificateDecorator.py
from DecoratorPattern.JewelryDecorator import JewelryDecorator
from DecoratorPattern.JewelryProduct import JewelryProduct
import time
 
# ===================== 5. 具体装饰器:流程扩展(业务环节) =====================
class CertificateDecorator(JewelryDecorator):
    """
    流程装饰器:开具鉴定证书(扩展加工流程)
    """
 
    def __init__(self, jewelry: JewelryProduct):
        """
 
        :param jewelry:
        """
        super().__init__(jewelry)
        self.certificate_fee = 300  # 证书服务费
 
    def get_price(self) -> float:
        """
 
        :return:
        """
        return self.jewelry.get_price() + self.certificate_fee
 
    def get_description(self) -> str:
        """
 
        :return:
        """
        return f"{self.jewelry.get_description()}(含国检鉴定证书)"
 
    def process(self) -> list[str]:
        """
 
        :return:
        """
        steps = self.jewelry.process()
 
        # 追加证书步骤
        time.sleep(0.5)
        steps.append("开具国家级珠宝鉴定证书")
        print(f"✅ 完成:{steps[-1]}")
 
        return steps
代码语言:javascript
复制
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:装饰器模式(Decorator 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/3/7 14:35
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : DecoratorBll.py
from DecoratorPattern.PlainGoldRing import PlainGoldRing
from DecoratorPattern.DiamondInlayDecorator import DiamondInlayDecorator
from DecoratorPattern.EngravingDecorator import EngravingDecorator
from DecoratorPattern.QualityCheckDecorator import QualityCheckDecorator
from DecoratorPattern.CertificateDecorator import CertificateDecorator
from DecoratorPattern.LuxuryPackagingDecorator import LuxuryPackagingDecorator
 
 
# ===================== 6. 测试:一体化定制珠宝 =====================
class DecoratorBll(object):
    """
    装饰器模式(Decorator Pattern)
    """
    def demo(self):
        """
        装饰器模式(Decorator Pattern)
        :return:
        """
        # 1. 创建基础珠宝:5克素金戒指
        basic_ring = PlainGoldRing(weight=5.0)
        print("=== 第一步:基础珠宝信息 ===")
        print(f"描述:{basic_ring.get_description()}")
        print(f"价格:{basic_ring.get_price()}元")
 
        # 2. 装饰1:添加实体属性(镶嵌钻石+雕花)
        decorated_ring = DiamondInlayDecorator(basic_ring, diamond_carat=0.3)
        decorated_ring = EngravingDecorator(decorated_ring, pattern="定制姓名缩写")
 
        # 3. 装饰2:添加业务流程(质检+证书+高端包装)
        decorated_ring = QualityCheckDecorator(decorated_ring)
        decorated_ring = CertificateDecorator(decorated_ring)
        decorated_ring = LuxuryPackagingDecorator(decorated_ring, package_type="定制皮质礼盒")
 
        # 4. 执行完整加工流程
        final_steps = decorated_ring.process()
 
        # 5. 输出最终结果
        print("\n=== 最终定制结果 ===")
        print(f"珠宝描述:{decorated_ring.get_description()}")
        print(f"总价:{decorated_ring.get_price()}元")
        print(f"完整加工流程:{final_steps}")

调用:

代码语言:javascript
复制
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: 设计模式 Design Patterns
# 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   : 学习
 
import Controller.CheckPatterns
 
 
def select_design_pattern() -> tuple[int, Controller.CheckPatterns.DesignPattern | None]:
    """
    返回 (序列号, 选中的枚举对象),退出则返回 (0, None)
    :return:
    """
    print("\n=== 方式3:用户选择展示 ===")
    print("可选设计模式(输入0或q退出):")
    for idx, pattern in enumerate(Controller.CheckPatterns.DesignPattern, 1):
        print(f"{idx}. {pattern._name_to_cn(pattern.name)}({pattern.name})")
    print("0. 退出")
 
    while True:
        user_input = input("\n请输入序号选择要展示的设计模式(输入0/q退出):").strip()
        if user_input in ("0", "q", "Q"):
            print("👋 退出选择流程")
            return (0, None)
 
        try:
            choice = int(user_input)
            if 1 <= choice <= len(Controller.CheckPatterns.DesignPattern):
                selected_pattern = list(Controller.CheckPatterns.DesignPattern)[choice - 1]
                print(f"✅ 你选择了序号:{choice}(对应{selected_pattern._name_to_cn(selected_pattern.name)})")
                return (choice, selected_pattern)  # 返回(序列号, 枚举对象)
            else:
                print(f"❌ 输入无效!请输入1-{len(Controller.CheckPatterns.DesignPattern)}之间的数字,或0/q退出")
        except ValueError:
            print("❌ 输入无效!请输入数字序号,或0/q退出")
 
def ask_continue() -> bool:
    """
    询问用户是否继续选择,返回True(继续)/False(退出)
    """
    while True:
        user_choice = input("\n是否继续选择其他设计模式?(y/n):").strip().lower()
        if user_choice == "y":
            return True
        elif user_choice == "n":
            print("👋 感谢使用,程序结束!")
            return False
        else:
            print("❌ 输入无效!请输入 y(继续)或 n(退出)")
 
 
if __name__ == '__main__':
 
    # 方式1:用户输入选择展示(交互版)
    '''
    print("\n=== 方式1:用户选择展示 ===")
    print("可选设计模式:")
    for idx, pattern in enumerate( bll.CheckPatterns.DesignPattern, 1):
        print(f"{idx}. {pattern._name_to_cn(pattern.name)}({pattern.name})")
 
    try:
        choice = int(input("\n请输入序号选择要展示的设计模式:"))
        selected_pattern = list( bll.CheckPatterns.DesignPattern)[choice - 1]
        selected_pattern.show_example()
    except (ValueError, IndexError):
        print("❌ 输入无效,请输入正确的序号!")
    '''
    # 2
 
    print("🎉 设计模式示例展示程序")
    while True:
        # 1. 选择设计模式
        selected_num, selected_pattern = select_design_pattern()
 
        # 2. 判断是否直接退出(输入0/q)
        if selected_num == 0:
            print("👋 程序结束!")
            break
 
        # 3. 执行选中的示例
        selected_pattern.show_example()
        print(f"\n📌 本次选择的序列号是:{selected_num}")
 
        # 4. 询问是否继续
        if not ask_continue():
            break  # 用户选择不继续,终止循环
 
    print('hi,welcome geovindu.')

输出:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2026-06-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档