news 2026/9/2 0:50:02

python: Bridge Pattern

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
python: Bridge Pattern

我们可以让 “业务流程” 和 “实体属性” 各自独立扩展(比如新增 “回收” 流程,或新增 “铂金” 材质,无需修改原有代码)。

项目结构:

# encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 9:45 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : JewelryEntity.py from dataclasses import dataclass from Model.GemEntity import GemEntity from Model.MaterialEntity import MaterialEntity # ========== 1. 珠宝实体类(无改动,复用) ========== @dataclass class JewelryEntity: """ 珠宝核心实体类(整合材质、宝石、基础属性) """ material: MaterialEntity """ 材质实体 """ gem: GemEntity """ 宝石实体 """ weight: float """ 珠宝总重量(克) """ style: str = "" """ 款式(可选) """ purity: float = 0.0 """ 实际纯度(可选) """ sale_price: float = 0.0 """ 售价(可选) """
# encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 10:22 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : JewelryGemImpl.py from abc import ABC, abstractmethod from Model.GemEntity import GemEntity # ========== 2. 桥接接口层(仅新增宝石回收残值计算,其余复用) ========== class JewelryGemImpl(ABC): """ 宝石接口实现层:基于宝石实体,提供宝石成本、回收残值计算能力" """ def __init__(self, gem_entity: GemEntity): """ :param gem_entity: """ self.entity = gem_entity @abstractmethod def calculate_gem_cost(self) -> float: """ 计算宝石成本 :return: """ pass @abstractmethod def calculate_gem_recycle_price(self) -> float: """ 新增:计算宝石回收残值 :return: """ pass # encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 9:47 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : JewelryMaterialImpl.py from abc import ABC, abstractmethod from Model.MaterialEntity import MaterialEntity # ========== 2. 桥接接口层(仅新增宝石回收残值计算,其余复用) ========== class JewelryMaterialImpl(ABC): """ 材质接口实现层:基于材质实体,提供成本、纯度校验、回收价计算等能力 """ def __init__(self, material_entity: MaterialEntity): """ :param material_entity: """ self.entity = material_entity # 组合实体类 @abstractmethod def calculate_material_cost(self, weight: float) -> float: """ 计算材质成本 :param weight: :return: """"" pass @abstractmethod def check_purity(self, actual_purity: float) -> bool: """ 校验纯度 :param actual_purity: :return: """ pass @abstractmethod def calculate_material_recycle_price(self, weight: float) -> float: """ 新增:计算材质回收价格 :param weight: :return: """ pass
# encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 10:28 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : RubyGemImpl.py from Interface.Bridge.JewelryGemImpl import JewelryGemImpl # ========== 3. 桥接实现层(仅新增宝石回收残值计算,其余复用) ========== class RubyGemImpl(JewelryGemImpl): """ 红宝石实现层 """ def calculate_gem_cost(self) -> float: """ :return: """ return self.entity.carat * self.entity.unit_price def calculate_gem_recycle_price(self) -> float: """ :return: """ # 红宝石回收残值 = 克拉数 * 单价 * 宝石回收折价率 return self.entity.carat * self.entity.unit_price * self.entity.gem_recycle_ratio # encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述: # 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/8 10:25 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : PlatinumMaterialImpl.py from Interface.Bridge.JewelryMaterialImpl import JewelryMaterialImpl # ========== 3. 桥接实现层(仅新增宝石回收残值计算,其余复用) ========== class PlatinumMaterialImpl(JewelryMaterialImpl): """ 铂金材质实现层 """ def calculate_material_cost(self, weight: float) -> float: """ :param weight: :return: """ return self.entity.cost_per_gram * weight def check_purity(self, actual_purity: float) -> bool: """ :param actual_purity: :return: """ return actual_purity >= self.entity.purity_standard def calculate_material_recycle_price(self, weight: float) -> float: """ :param weight: :return: """ # 铂金回收价 = 材质成本 * 重量 * 回收折价率 return self.entity.cost_per_gram * weight * self.entity.recycle_ratio # encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述: # 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/8 10:24 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : GoldMaterialImpl.py from Interface.Bridge.JewelryMaterialImpl import JewelryMaterialImpl # ========== 3. 桥接实现层(仅新增宝石回收残值计算,其余复用) ========== class GoldMaterialImpl(JewelryMaterialImpl): """ 黄金材质实现层 """ def calculate_material_cost(self, weight: float) -> float: """ :param weight: :return: """ return self.entity.cost_per_gram * weight def check_purity(self, actual_purity: float) -> bool: """ :param actual_purity: :return: """ return actual_purity >= self.entity.purity_standard def calculate_material_recycle_price(self, weight: float) -> float: """ :param weight: :return: """ # 黄金回收价 = 材质成本 * 重量 * 回收折价率 return self.entity.cost_per_gram * weight * self.entity.recycle_ratio # encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 10:28 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : DiamondGemImpl.py from Interface.Bridge.JewelryGemImpl import JewelryGemImpl # ========== 3. 桥接实现层(仅新增宝石回收残值计算,其余复用) ========== class DiamondGemImpl(JewelryGemImpl): """ 钻石实现层 """ def calculate_gem_cost(self) -> float: """ :return: """ return self.entity.carat * self.entity.unit_price def calculate_gem_recycle_price(self) -> float: """ :return: """ # 钻石回收残值 = 克拉数 * 单价 * 宝石回收折价率 return self.entity.carat * self.entity.unit_price * self.entity.gem_recycle_ratio
# encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 10:33 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : JewelryBusiness.py from abc import ABC, abstractmethod from Model.GemEntity import GemEntity from Model.MaterialEntity import MaterialEntity from Model.JewelryEntity import JewelryEntity from Interface.Bridge.JewelryMaterialImpl import JewelryMaterialImpl from Interface.Bridge.JewelryGemImpl import JewelryGemImpl # ========== 4. 桥接抽象层接口 ========== class JewelryBusiness(ABC): """ 珠宝业务流程抽象接口层 """ def __init__(self, jewelry_entity: JewelryEntity, material_impl: JewelryMaterialImpl, gem_impl: JewelryGemImpl): self.entity = jewelry_entity # 珠宝实体(核心数据) self.material_impl = material_impl # 材质能力实现 self.gem_impl = gem_impl # 宝石能力实现 @abstractmethod def process(self) -> str: """ 执行业务流程 :return: """ pass
# encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 10:44 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : SaleBusiness.py from Interface.Bridge.JewelryBusiness import JewelryBusiness # ========== 5. 桥接业务层(新增回收业务流程) ========== class SaleBusiness(JewelryBusiness): """ 原有业务流程:销售(复用) """ def process(self) -> str: """ :return: """ total_cost = self.material_impl.calculate_material_cost(self.entity.weight) + self.gem_impl.calculate_gem_cost() profit = self.entity.sale_price - total_cost return ( f"【销售流程】\n" f"- 珠宝实体属性:\n" f" ✅ 材质:{self.entity.material.name} | 宝石:{self.entity.gem.type}\n" f" ✅ 重量:{self.entity.weight}克 | 售价:{self.entity.sale_price:.2f}元\n" f"- 利润核算:总成本{total_cost:.2f}元 → 利润{profit:.2f}元\n" f"- 流程完成:已开具发票,质保期2年" ) # encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 10:46 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : RecycleBusiness.py from Interface.Bridge.JewelryBusiness import JewelryBusiness from Model.MaterialEntity import MaterialEntity from Model.GemEntity import GemEntity from Model.JewelryEntity import JewelryEntity from Interface.Bridge.JewelryGemImpl import JewelryGemImpl from Interface.Bridge.JewelryMaterialImpl import JewelryMaterialImpl # ========== 5. 桥接业务层(新增回收业务流程) ========== # 新增业务流程:回收 class RecycleBusiness(JewelryBusiness): """ 珠宝回收业务流程 """ def __init__(self, jewelry_entity: JewelryEntity, material_impl: JewelryMaterialImpl, gem_impl: JewelryGemImpl, check_result: bool): """ :param jewelry_entity: :param material_impl: :param gem_impl: :param check_result: """ super().__init__(jewelry_entity, material_impl, gem_impl) self.check_result = check_result # 回收前质检结果(是否合格) def process(self) -> str: """ :return: """ if not self.check_result: return ( f"【回收流程】\n" f"- 珠宝实体属性:{self.entity.material.name} + {self.entity.gem.type},重量{self.entity.weight}克\n" f"- 回收结果:质检不合格(纯度{self.entity.purity}% < 标准{self.entity.material.purity_standard}%),拒绝回收\n" f"- 流程完成:回收申请驳回" ) # 计算回收价格(材质+宝石残值) material_recycle_price = self.material_impl.calculate_material_recycle_price(self.entity.weight) gem_recycle_price = self.gem_impl.calculate_gem_recycle_price() total_recycle_price = material_recycle_price + gem_recycle_price return ( f"【回收流程】\n" f"- 珠宝实体属性:\n" f" ✅ 材质:{self.entity.material.name}(回收折价率{self.entity.material.recycle_ratio})\n" f" ✅ 宝石:{self.entity.gem.type}({self.entity.gem.carat}克拉,回收折价率{self.entity.gem.gem_recycle_ratio})\n" f" ✅ 重量:{self.entity.weight}克 | 实际纯度:{self.entity.purity}%\n" f"- 回收价格核算:\n" f" ✅ 材质回收价:{material_recycle_price:.2f}元\n" f" ✅ 宝石残值:{gem_recycle_price:.2f}元\n" f" ✅ 总回收价:{total_recycle_price:.2f}元\n" f"- 流程完成:回收协议已签署,款项将在24小时内到账" ) # encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 10:42 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : InspectionBusiness.py from Interface.Bridge.JewelryBusiness import JewelryBusiness # ========== 5. 桥接业务层(新增回收业务流程) ========== class InspectionBusiness(JewelryBusiness): """ 原有业务流程:质检(复用) """ def process(self) -> str: """ :return: """ is_qualified = self.material_impl.check_purity(self.entity.purity) return ( f"【质检流程】\n" f"- 珠宝实体属性:\n" f" ✅ 材质:{self.entity.material.name}(标准纯度{self.entity.material.purity_standard}%)\n" f" ✅ 宝石:{self.entity.gem.type}({self.entity.gem.carat}克拉)\n" f" ✅ 重量:{self.entity.weight}克 | 实际纯度:{self.entity.purity}%\n" f"- 质检结果:{'合格' if is_qualified else '不合格'}({self.entity.material.name}需≥{self.entity.material.purity_standard}%)\n" f"- 流程完成:质检报告已生成" ) # encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 10:37 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : CustomizeBusiness.py from Interface.Bridge.JewelryBusiness import JewelryBusiness # ========== 5. 桥接业务层(新增回收业务流程) ========== class CustomizeBusiness(JewelryBusiness): """ 原有业务流程:定制业务(复用) """ def process(self) -> str: """ :return: """ material_cost = self.material_impl.calculate_material_cost(self.entity.weight) gem_cost = self.gem_impl.calculate_gem_cost() total_cost = material_cost + gem_cost return ( f"【定制流程】\n" f"- 珠宝实体属性:\n" f" ✅ 材质:{self.entity.material.name}(每克{self.entity.material.cost_per_gram}元)\n" f" ✅ 宝石:{self.entity.gem.type}({self.entity.gem.carat}克拉,每克拉{self.entity.gem.unit_price}元)\n" f" ✅ 重量:{self.entity.weight}克 | 款式:{self.entity.style}\n" f"- 成本核算:材质成本{material_cost:.2f}元 + 宝石成本{gem_cost:.2f}元 = 总成本{total_cost:.2f}元\n" f"- 流程完成:定制订单已提交,预计7个工作日完成" )
# encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:桥接模式 Bridge 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/8 11:22 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : BridgeBll.py from Model.GemEntity import GemEntity from Model.MaterialEntity import MaterialEntity from Model.JewelryEntity import JewelryEntity from BridgePattern.DiamondGemImpl import DiamondGemImpl from BridgePattern.GoldMaterialImpl import GoldMaterialImpl from BridgePattern.RecycleBusiness import RecycleBusiness from BridgePattern.SaleBusiness import SaleBusiness from BridgePattern.CustomizeBusiness import CustomizeBusiness from BridgePattern.InspectionBusiness import InspectionBusiness # ========== 6 客户端 测试代码 ========== class BridgeBll(object): """ 桥接模式 Bridge Pattern """ def demo(self): """ 桥接模式 Bridge Pattern :return: """ # 1. 创建实体类(含回收相关属性) # 材质实体:足金999(每克580元,标准纯度99.9%,回收折价率0.95) gold_entity = MaterialEntity( name="足金999", cost_per_gram=580.0, purity_standard=99.9, recycle_ratio=0.95 # 黄金回收折价率95% ) # 宝石实体:1.2克拉钻石(每克拉80000元,回收折价率0.6) diamond_entity = GemEntity( type="钻石", carat=1.2, unit_price=80000.0, gem_recycle_ratio=0.6 # 钻石回收折价率60% ) # 珠宝实体:18克足金钻石戒指(纯度99.95%) jewelry_entity = JewelryEntity( material=gold_entity, gem=diamond_entity, weight=18.0, style="经典六爪戒指", purity=99.95 # 实际纯度(合格) ) # 2. 创建实现层 material_impl = GoldMaterialImpl(gold_entity) gem_impl = DiamondGemImpl(diamond_entity) # 3. 执行所有业务流程(含回收) print("=== 1. 定制流程 ===") customize_business = CustomizeBusiness(jewelry_entity, material_impl, gem_impl) print(customize_business.process()) print("\n=== 2. 质检流程 ===") inspection_business = InspectionBusiness(jewelry_entity, material_impl, gem_impl) print(inspection_business.process()) print("\n=== 3. 销售流程 ===") jewelry_entity.sale_price = 150000.0 # 设置售价 sale_business = SaleBusiness(jewelry_entity, material_impl, gem_impl) print(sale_business.process()) print("\n=== 4. 回收流程(合格) ===") recycle_business = RecycleBusiness(jewelry_entity, material_impl, gem_impl, check_result=True) print(recycle_business.process()) # 测试:回收流程(质检不合格) print("\n=== 5. 回收流程(不合格) ===") jewelry_entity.purity = 99.8 # 修改为不合格纯度 recycle_business_fail = RecycleBusiness(jewelry_entity, material_impl, gem_impl, check_result=False) print(recycle_business_fail.process())
# encoding: utf-8 # 版权所有 2026 ©涂聚文有限公司™ ® # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 # 描述:计模式 Design Patterns # 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/4 21:47 # User : geovindu # Product : PyCharm # Project : pydesginpattern # File : CheckPatterns.py ''' 创建型模式 Creational Patterns 抽象工厂Abstract Factory 简单工厂模式 Simple Factory Pattern 生成器 Builder 工厂方法 Factory Method 原型 Prototype 单例 Singleton 结构型模式 Structural Patterns 适配器Adapter 桥接Bridge 组合Composite 装饰Decorator 外观Facade 享元Flyweight 代理Proxy 行为模式 Behavioral Patterns 责任链Chain of Responsibility 迭代器Iterator 备忘录Memento 状态State 模板方法Template Method 命令Command 中介者Mediator 观察者Observer 策略Strategy 访问者Visitor null object Pattern ''' from enum import Enum, auto # 导入枚举相关模块 # 行为模式 Behavioral Patterns 10 import bll.ChainofResponsibilityBll import bll.MementoBll import bll.CommandBll import bll.StateBll import bll.TemplateMethodBll import bll.VisitorBll import bll.StrategyBll import bll.ObserveBll import bll.MediatorBll import bll.IteratorBll #结构型模式 Structural Patterns 7 import bll.ProxyBll import bll.FlyweightBll import bll.FacadeBll import bll.DecoratorBll import bll.CompositeBll import bll.BridgeBll import bll.AdapterBll # 创建型模式 Creational Patterns 6 import bll.AbstractFactoryBll import bll.SingletonBll import bll.PrototypeBll import bll.BuilderBll import bll.FactoryBll import bll.SimpleFactoryBll import bll.FactoryMethodBll import bll.NullObjectBll # ====================== 7。 枚举类定义:管理所有设计模式示例 ====================== class DesignPattern(Enum): """ 设计模式枚举 - 每个枚举成员对应一个设计模式的示例函数 """ Memento = auto() """ 备忘录模式 """ Command = auto() # """ 命令模式 """ State = auto() # """ 状态模式 """ TemplateMethod=auto() # """ 模板方法模式 """ Visitor=auto() # """ 访问者模式 """ Strategy=auto() # """ 策略模式 """ Observe=auto() # """ 观察者模式 """ Mediator=auto() # """ 中介者模式 """ Iterator=auto() # """ 迭代器模式 """ ChainofResponsibility=auto() # """ 责任链模式 """ Proxy=auto() # """ 代理模式 """ Flyweight=auto() """ 享元模式 """ Facade=auto """ 外观模式 """ Decorator=auto() """ 装饰器模式 """ Composite=auto() """ 组合模式 """ Singleton=auto() """ 单例模式 """ Prototype=auto() """ 原型模式 """ Bridge=auto() """ 桥接模式 """ Adapter=auto() """ 适配器模式 """ Builder=auto() """ 生成器模式 """ AbstractFactory=auto() """ 抽象工厂模式 """ Factory=auto() """ 工厂模式 """ SimpleFactory=auto() """ 简单工厂模式 """ FactoryMethod=auto() """ 工厂方法模式 """ NullObject=auto() """ 空对象模式 """ def show_example(self): """ 枚举成员方法:根据当前枚举值执行对应的示例函数 :return: """ pattern_handlers = { DesignPattern.Memento:lambda:(bll.MementoBll.MementoBll().demo()), DesignPattern.Command:lambda:(bll.CommandBll.CommandBll().demo()), DesignPattern.State:lambda:(bll.StateBll.StateBll().demo()), DesignPattern.TemplateMethod:lambda:(bll.TemplateMethodBll.TemplateMethodBll().demo()), DesignPattern.Visitor:lambda:(bll.VisitorBll.VisitorBll().demo()), DesignPattern.Strategy:lambda:(bll.StrategyBll.StrategyBll().demo()), DesignPattern.Observe:lambda:(bll.ObserveBll.ObserveBll().demo()), DesignPattern.Mediator:lambda:(bll.MediatorBll.MediatorBll().demo()), DesignPattern.Iterator:lambda:(bll.IteratorBll.IteratorBll().demo()), DesignPattern.ChainofResponsibility:lambda:(bll.ChainofResponsibilityBll.ChainofResponsibilityBll().dudemo()), DesignPattern.Proxy:lambda:(bll.ProxyBll.ProxyBll().demo()), DesignPattern.Flyweight:lambda:(bll.FlyweightBll.FlyweightBll().demo()), DesignPattern.Facade:lambda :(bll.FacadeBll.FacadeBll().demo()), DesignPattern.Decorator:lambda :(bll.DecoratorBll.DecoratorBll().demo()), DesignPattern.Composite:lambda:(bll.CompositeBll.CompositeBll().demo()), DesignPattern.Singleton:lambda:(bll.SingletonBll.SingletonBll().demo()), DesignPattern.Prototype:lambda:(bll.PrototypeBll.PrototypeBll().demo()), DesignPattern.Bridge:lambda:(bll.BridgeBll.BridgeBll().demo()), DesignPattern.Adapter:lambda:(bll.AdapterBll.AdapterBll().demo()), DesignPattern.Builder:lambda:(bll.BuilderBll.BuilderBll().demo()), DesignPattern.AbstractFactory:lambda:(bll.AbstractFactoryBll.AbstractFactoryBll().demo()), DesignPattern.Factory:lambda:(bll.FactoryBll.FactoryBll().demo()), DesignPattern.SimpleFactory:lambda:(bll.SimpleFactoryBll.SimpleFactoryBll().demo()), DesignPattern.FactoryMethod:lambda:(bll.FactoryMethodBll.FactoryMethodBll().demo()), DesignPattern.NullObject:lambda:(bll.NullObjectBll.NullObjectBll().demo()), } # 获取当前枚举对应的示例函数并执行 handler = pattern_handlers.get(self) if handler: print(f"\n===== 展示【{self.name}({self._name_to_cn(self.name)})】示例 =====") handler() else: print(f"❌ 暂未实现{self.name}的示例") @staticmethod def _name_to_cn(name: str) -> str: """ 枚举名称转中文,提升可读性 :param name: :return: """ cn_map = { "Memento": "备忘录模式", "Command": "单例模式", "State": "命令模式", "TemplateMethod": "模板方法模式", "Visitor": "模板方法模式", "Strategy": "策略模式", "Observe": "观察者模式", "Mediator": "中介者模式", "Iterator": "迭代器模式", "ChainofResponsibility": "责任链模式", "Proxy": "代理模式", "Flyweight": "享元模式", "Facade":"外观模式", "Decorator":"装饰器模式", "Composite": "组合模式", "Singleton":"单例模式", "Prototype":"原型模式", "Bridge":"桥接模式", "Adapter":"适配器模式", "Builder":"生成器模式", "AbstractFactory":"抽象工厂模式", "Factory":"工厂模式", "SimpleFactory":"简单工厂模式", "FactoryMethod":"工厂方法模式", "NullObject":"空对象模式", } return cn_map.get(name, name)

调用:

# 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.')

输出:

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/2 0:49:29

YOLOv1论文研读

YOLOv1最大的创新点在于它提出并实现了将目标检测定义回归问题&#xff0c;它不再像之前的模型一样基于分类器方法&#xff0c;而是通过与检测性能直接对应的损失函数进行训练&#xff0c;从而实现了一个端到端的统一网络&#xff0c;做到只需“看一眼”就能直接从完整图像中输…

作者头像 李华
网站建设 2026/7/14 17:27:47

Ubuntu 22.04系统国内镜像源配置指南

备份原配置文件 在修改前需备份原文件&#xff0c;防止配置错误导致系统异常&#xff1a; sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak编辑源文件 使用文本编辑器&#xff08;如vi或nano&#xff09;修改源文件&#xff1a; sudo vi /etc/apt/sources.list国内镜…

作者头像 李华
网站建设 2026/7/14 17:27:45

c#311 引用类型 out ref task async

c# 基础 值类型 引用类型 引用类型 class object array 接口、委托等 保存在堆中 clr 管理堆 .net的核心组件 管 代码执行、内存分配、垃圾回收等 object 所有类的基类 C# 中所有类型&#xff08;值类型 引用类型&#xff09;的最终基类&#xff0c;任何类型都可以隐式转换为…

作者头像 李华
网站建设 2026/7/14 17:27:49

为什么放弃 ChatGPT 客户端,选择 OpenClaw 做你的全能业务网关?

一、 引言&#xff1a;你的 AI 生产力&#xff0c;正在被“聊天框”封印 现象剖析 回想一下你每天使用 ChatGPT Web 客户端的场景&#xff1a;你需要手动将数据从 Excel 复制出来&#xff0c;粘贴到对话框里&#xff1b;聊了几天后&#xff0c;AI 开始频繁遗忘早期设定的背景&a…

作者头像 李华