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_gram580.0, purity_standard99.9, recycle_ratio0.95 # 黄金回收折价率95% ) # 宝石实体1.2克拉钻石每克拉80000元回收折价率0.6 diamond_entity GemEntity( type钻石, carat1.2, unit_price80000.0, gem_recycle_ratio0.6 # 钻石回收折价率60% ) # 珠宝实体18克足金钻石戒指纯度99.95% jewelry_entity JewelryEntity( materialgold_entity, gemdiamond_entity, weight18.0, style经典六爪戒指, purity99.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_resultTrue) print(recycle_business.process()) # 测试回收流程质检不合格 print(\n 5. 回收流程不合格 ) jewelry_entity.purity 99.8 # 修改为不合格纯度 recycle_business_fail RecycleBusiness(jewelry_entity, material_impl, gem_impl, check_resultFalse) 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() # 状态模式 TemplateMethodauto() # 模板方法模式 Visitorauto() # 访问者模式 Strategyauto() # 策略模式 Observeauto() # 观察者模式 Mediatorauto() # 中介者模式 Iteratorauto() # 迭代器模式 ChainofResponsibilityauto() # 责任链模式 Proxyauto() # 代理模式 Flyweightauto() 享元模式 Facadeauto 外观模式 Decoratorauto() 装饰器模式 Compositeauto() 组合模式 Singletonauto() 单例模式 Prototypeauto() 原型模式 Bridgeauto() 桥接模式 Adapterauto() 适配器模式 Builderauto() 生成器模式 AbstractFactoryauto() 抽象工厂模式 Factoryauto() 工厂模式 SimpleFactoryauto() 简单工厂模式 FactoryMethodauto() 工厂方法模式 NullObjectauto() 空对象模式 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.)输出

相关新闻

python自定义IP输入栏,Tkinter PyQT分别实现

python自定义IP输入栏,Tkinter PyQT分别实现

1.TKinter实现""" Windows 10 风格 IP 地址输入控件 - Tkinter 版本这个模块提供了高度还原 Windows 10 风格的 IP 地址输入控件,具备以下特性:主要功能:1. 自动焦点管理 - 输入 3 位数字后自动跳转到下一段2. 智能输入验证 - 只允许 0-2…

2026/7/3 0:27:03 阅读更多 →
【避坑指南】ConcurrentHashMap 并发操作的致命陷阱

【避坑指南】ConcurrentHashMap 并发操作的致命陷阱

注:本文是笔者在学习【极客时间】业务开发常见错误过程中,整理记载的个人学习和思考笔记 在高并发编程中,ConcurrentHashMap 因线程安全特性被广泛使用,但很多开发者误以为「用了 ConcurrentHashMap 就万事大吉」,却忽…

2026/7/3 8:36:43 阅读更多 →
【RTX4070】12g显存 ComfyUI AI 视频 (T2V/I2V) 避坑与实战指南

【RTX4070】12g显存 ComfyUI AI 视频 (T2V/I2V) 避坑与实战指南

进阶之路:资深玩家的 ComfyUI AI 视频 (T2V/I2V) 避坑与实战指南 对于习惯了代码逻辑的开发者来说,初入 ComfyUI 的感觉就像是接手了一个没有说明文档的开源微服务架构。节点满天飞、连线如乱麻、动不动就爆显存(OOM)或者产出“电…

2026/5/17 12:55:38 阅读更多 →

最新新闻

nginx-auth-ldap性能优化终极指南:连接池配置与缓存策略提升认证效率

nginx-auth-ldap性能优化终极指南:连接池配置与缓存策略提升认证效率

nginx-auth-ldap性能优化终极指南:连接池配置与缓存策略提升认证效率 【免费下载链接】nginx-auth-ldap LDAP authentication module for nginx 项目地址: https://gitcode.com/gh_mirrors/ng/nginx-auth-ldap nginx-auth-ldap是一个强大的LDAP认证模块&…

2026/7/4 6:26:47 阅读更多 →
3个关键场景教你轻松拯救即将消失的Flash内容

3个关键场景教你轻松拯救即将消失的Flash内容

3个关键场景教你轻松拯救即将消失的Flash内容 【免费下载链接】jpexs-decompiler JPEXS Free Flash Decompiler 项目地址: https://gitcode.com/gh_mirrors/jp/jpexs-decompiler 随着Adobe Flash正式退役,无数经典的Flash动画、游戏和互动内容正面临永久消失…

2026/7/4 6:26:47 阅读更多 →
Gloom的Kotlin Multiplatform架构解析:跨平台开发的最佳实践

Gloom的Kotlin Multiplatform架构解析:跨平台开发的最佳实践

Gloom的Kotlin Multiplatform架构解析:跨平台开发的最佳实践 【免费下载链接】Gloom GitHub reimagined with Material You 项目地址: https://gitcode.com/gh_mirrors/glo/Gloom 在当今多平台应用开发的时代,Gloom项目为我们展示了一个基于Kotli…

2026/7/4 6:24:46 阅读更多 →
Primer设计系统设计原则解析:GitHub Zen哲学在设计中的应用

Primer设计系统设计原则解析:GitHub Zen哲学在设计中的应用

Primer设计系统设计原则解析:GitHub Zen哲学在设计中的应用 【免费下载链接】design Primer Design Guidelines 项目地址: https://gitcode.com/gh_mirrors/des/design Primer设计系统是GitHub的官方设计系统,它将GitHub Zen哲学融入到界面设计的…

2026/7/4 6:24:46 阅读更多 →
SQL索引优化:SQL Ultimate Course查询性能提升指南

SQL索引优化:SQL Ultimate Course查询性能提升指南

SQL索引优化:SQL Ultimate Course查询性能提升指南 【免费下载链接】sql-ultimate-course The most comprehensive SQL guide from a real-world expert! Learn everything from basics to advanced queries, optimizations, and real-world SQL 项目地址: https…

2026/7/4 6:20:45 阅读更多 →
ZFS-inplace-rebalancing在大型存储环境中的最佳实践:终极数据平衡指南 [特殊字符]

ZFS-inplace-rebalancing在大型存储环境中的最佳实践:终极数据平衡指南 [特殊字符]

ZFS-inplace-rebalancing在大型存储环境中的最佳实践:终极数据平衡指南 🚀 【免费下载链接】zfs-inplace-rebalancing Simple bash script to rebalance pool data between all mirrors when adding vdevs to a pool. 项目地址: https://gitcode.com/g…

2026/7/4 6:18:45 阅读更多 →

日新闻

Memcached 1.6.43 发布:关键安全修复版本,多项问题得到解决

Memcached 1.6.43 发布:关键安全修复版本,多项问题得到解决

Memcached 1.6.43 正式发布,这是一个关键的安全修复版本,修复了多个方面的问题,还对部分功能进行了优化。 安全修复亮点 此次发布在安全修复上表现突出。binprot 避免了项目引用计数溢出,mcmc 因安全问题提升了上游版本号&#xf…

2026/7/4 0:04:29 阅读更多 →
终极指南:使用HMCL启动器跨平台畅玩Minecraft的完整解决方案

终极指南:使用HMCL启动器跨平台畅玩Minecraft的完整解决方案

终极指南:使用HMCL启动器跨平台畅玩Minecraft的完整解决方案 【免费下载链接】HMCL A Minecraft Launcher which is multi-functional, cross-platform and popular 项目地址: https://gitcode.com/gh_mirrors/hm/HMCL HMCL(Hello Minecraft! Lau…

2026/7/4 0:06:29 阅读更多 →
KMX63与PIC18F66K40在嵌入式HMI中的硬件协同与低功耗设计

KMX63与PIC18F66K40在嵌入式HMI中的硬件协同与低功耗设计

1. KMX63与PIC18F66K40的硬件协同架构解析KMX63作为一款三轴加速度计和磁力计组合传感器,与PIC18F66K40微控制器的搭配堪称嵌入式HMI开发的黄金组合。这套硬件组合的核心优势在于KMX63提供的高精度运动感知能力与PIC18F66K40强大的信号处理能力形成了完美互补。KMX6…

2026/7/4 0:06:29 阅读更多 →

周新闻

月新闻