在珠宝行业中,一款珠宝(如钻戒、手镯)的属性复杂(材质、宝石参数、工艺),且批量定制同款珠宝时,重复定义基础属性会增加成本、易出错。用原型模式克隆基础款,仅微调差异化属性(证书号、定制刻字),能大幅提升业务效率。
python
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: 原型模式 Prototype 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 16:19
# User : geovindu
# Product : PyCharm
# Project : pydesginpattern
# File : JewelryPrototype.py
import copy
from datetime import datetime
# ===================== 1. 珠宝原型抽象类(定义通用属性和业务接口) =====================
class JewelryPrototype:
"""
珠宝原型抽象类:封装通用属性和核心业务流程
"""
def __init__(self, jewelry_type: str, material: str, gem_params: dict, craft: str, base_price: float):
"""
【基础属性】- 同款珠宝通用,克隆时保留(无需重复定义)
:param jewelry_type: 珠宝类型:钻戒/项链/手镯
:param material: 材质:铂金950/18K金/足银
:param gem_params: 宝石参数:钻石(净度/颜色/重量)、珍珠(直径/光泽)
:param craft: 工艺:六爪镶/微镶/花丝工艺
:param base_price: 基础定价(元)
"""
# 【基础属性】- 同款珠宝通用,克隆时保留(无需重复定义)
self.jewelry_type = jewelry_type # 珠宝类型:钻戒/项链/手镯
self.material = material # 材质:铂金950/18K金/足银
self.gem_params = gem_params # 宝石参数:钻石(净度/颜色/重量)、珍珠(直径/光泽)
self.craft = craft # 工艺:六爪镶/微镶/花丝工艺
self.base_price = base_price # 基础定价(元)
# 【差异化属性】- 每个实例唯一,克隆后重置(需单独设置)
self.certificate_no = None # 鉴定证书编号(唯一)
self.custom_engraving = None # 客户定制刻字(如姓名、日期)
self.final_price = None # 最终定价(基础价+定制费)
self.outbound_time = None # 出库时间
def clone(self):
"""
核心:深克隆方法(保证原型与克隆对象完全独立)
:return:
"""
# 深拷贝:复制所有属性(包括字典、列表等可变对象)
cloned_jewelry = copy.deepcopy(self)
# 克隆后重置差异化属性(仅保留基础属性)
cloned_jewelry.certificate_no = None
cloned_jewelry.custom_engraving = None
cloned_jewelry.final_price = None
cloned_jewelry.outbound_time = None
print(f"✅ 克隆{self.jewelry_type}原型成功(基础属性保留,差异化属性已重置)")
return cloned_jewelry
# ===================== 核心业务流程方法 =====================
def generate_certificate(self, cert_no: str):
"""
业务流程1:生成唯一鉴定证书(珠宝核心合规流程)
:param cert_no:
:return:
"""
self.certificate_no = cert_no
print(f"📜 【{self.jewelry_type}】生成鉴定证书,编号:{cert_no}")
def customize_engraving(self, text: str):
"""
业务流程2:客户定制刻字(个性化需求)
:param text:
:return:
"""
self.custom_engraving = text
print(f"✍️ 【{self.jewelry_type}】完成定制刻字:{text}")
def calculate_final_price(self, custom_fee: float = 0):
"""业务流程3:计算最终定价(基础价+定制费)"""
self.final_price = self.base_price + custom_fee
print(
f"💰 【{self.jewelry_type}】定价完成:基础价{self.base_price}元 + 定制费{custom_fee}元 = 最终价{self.final_price}元")
def outbound(self):
"""
业务流程4:出库(记录出库时间,完成交付)
:return:
"""
self.outbound_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"🚚 【{self.jewelry_type}】出库完成,出库时间:{self.outbound_time}")
def show_jewelry_info(self):
"""
展示珠宝完整信息(属性+业务状态)
:return:
"""
print("\n" + "-" * 60)
print(f"【{self.jewelry_type} 完整信息】")
print(f"1. 基础属性:")
print(f" - 材质:{self.material}")
print(f" - 宝石参数:{self.gem_params}")
print(f" - 工艺:{self.craft}")
print(f" - 基础定价:{self.base_price}元")
print(f"2. 业务状态:")
print(f" - 证书编号:{self.certificate_no or '未生成'}")
print(f" - 定制刻字:{self.custom_engraving or '无'}")
print(f" - 最终定价:{self.final_price or '未定价'}元")
print(f" - 出库时间:{self.outbound_time or '未出库'}")
print("-" * 60 + "\n")
python
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:原型模式 Prototype 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 16:22
# User : geovindu
# Product : PyCharm
# Project : pydesginpattern
# File : DiamondRing.py
from Model.JewelryPrototype import JewelryPrototype
# ===================== 2. 具体原型类:钻戒(实现基础款原型) =====================
class DiamondRing(JewelryPrototype):
"""
钻戒原型类:基础款钻戒模板
"""
def __init__(self):
"""
初始化「基础款50分钻戒」的通用属性(珠宝店标准模板)
"""
super().__init__(
jewelry_type="钻戒",
material="铂金950",
gem_params={
"钻石重量": "0.5克拉",
"净度": "VS1",
"颜色": "D色",
"切工": "3EX"
},
craft="六爪镶",
base_price=15800.0 # 基础定价
)
print(f"🎯 基础款钻戒原型创建完成(可批量克隆)")
python
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:原型模式 Prototype 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 16:23
# User : geovindu
# Product : PyCharm
# Project : pydesginpattern
# File : PearlNecklace.py
from Model.JewelryPrototype import JewelryPrototype
# ===================== 3. 具体原型类:珍珠项链(实现基础款原型) =====================
class PearlNecklace(JewelryPrototype):
"""
珍珠项链原型类:基础款项链模板
"""
def __init__(self):
"""
初始化「基础款Akoya珍珠项链」的通用属性
"""
super().__init__(
jewelry_type="珍珠项链",
material="18K金",
gem_params={
"珍珠品种": "Akoya",
"直径": "8-9mm",
"光泽": "极强光",
"瑕疵": "微瑕"
},
craft="手工串珠",
base_price=8999.0
)
print(f"🎯 基础款珍珠项链原型创建完成(可批量克隆)")
python
# encoding: utf-8
# 版权所有 2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:原型模式 Prototype 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 16:24
# User : geovindu
# Product : PyCharm
# Project : pydesginpattern
# File : PrototypeBll.py
from PrototypePattern.DiamondRing import DiamondRing
from PrototypePattern.PearlNecklace import PearlNecklace
# ===================== 4. 完整业务流程演示 =====================
class PrototypeBll(object):
"""
原型模式
"""
def demo(self):
"""
原型模式
:return:
"""
# 步骤1:创建基础款原型(珠宝店的标准模板)
diamond_ring_prototype = DiamondRing()
pearl_necklace_prototype = PearlNecklace()
# 步骤2:克隆钻戒原型 → 客户A定制款(仅修改差异化属性)
print("\n===== 客户A定制钻戒流程 =====")
customer_a_ring = diamond_ring_prototype.clone()
customer_a_ring.generate_certificate("GIC20260307001") # 生成唯一证书
customer_a_ring.customize_engraving("A&L 2026.03.07") # 定制刻字(个性化需求)
customer_a_ring.calculate_final_price(custom_fee=1000) # 刻字定制费1000元
customer_a_ring.outbound() # 出库交付
customer_a_ring.show_jewelry_info() # 展示最终信息
# 步骤3:克隆珍珠项链原型 → 客户B定制款(无额外定制费)
print("\n===== 客户B定制珍珠项链流程 =====")
customer_b_necklace = pearl_necklace_prototype.clone()
customer_b_necklace.generate_certificate("GIC20260307002")
customer_b_necklace.calculate_final_price() # 无定制费
customer_b_necklace.outbound()
customer_b_necklace.show_jewelry_info()
# 验证:原型与克隆对象完全独立(修改克隆对象不影响原型)
print("\n===== 原型与克隆对象独立性验证 =====")
print(f"原型钻戒证书编号:{diamond_ring_prototype.certificate_no}(应为None)")
print(f"客户A钻戒证书编号:{customer_a_ring.certificate_no}(应为GIC20260307001)")
调用:
python
# 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.')
输出:
