在软件开发中,我们经常遇到这样的困境:当业务需求变化时,不得不修改大量现有代码。特别是在珠宝行业这样的领域,业务流程(如销售、质检、回收)和实体属性(如材质、宝石)都可能独立变化。传统设计会导致代码高度耦合,任何一方的修改都可能引发连锁反应。
桥接模式(Bridge Pattern)正是解决这类问题的利器。它通过将抽象部分与实现部分分离,使它们可以独立变化。在珠宝管理系统中,这意味着我们可以:
下面我将通过一个完整的珠宝业务系统案例,展示如何用Python实现这一优雅的设计方案。
我们的珠宝管理系统采用三层架构设计:
实体层:包含珠宝核心数据模型
JewelryEntity:聚合材质和宝石信息MaterialEntity:定义材质属性GemEntity:定义宝石属性桥接接口层:定义业务能力接口
JewelryMaterialImpl:材质相关操作JewelryGemImpl:宝石相关操作业务抽象层:处理具体业务流程
JewelryBusiness:业务基类python复制# 实体层示例
@dataclass
class JewelryEntity:
material: MaterialEntity # 材质实体
gem: GemEntity # 宝石实体
weight: float # 重量(克)
style: str = "" # 款式
purity: float = 0.0 # 实际纯度
sale_price: float = 0.0 # 售价
这种设计的精妙之处在于:当需要新增业务或实体时,只需扩展而不用修改现有代码。比如要增加"租赁"业务,只需新建RentBusiness类;要添加"翡翠"宝石,只需实现新的JadeGemImpl。
材质接口定义了材质相关的核心能力:
python复制class JewelryMaterialImpl(ABC):
@abstractmethod
def calculate_material_cost(self, weight: float) -> float:
"""计算材质成本"""
@abstractmethod
def check_purity(self, actual_purity: float) -> bool:
"""纯度校验"""
@abstractmethod
def calculate_material_recycle_price(self, weight: float) -> float:
"""新增:计算材质回收价格"""
宝石接口同样采用抽象基类定义:
python复制class JewelryGemImpl(ABC):
@abstractmethod
def calculate_gem_cost(self) -> float:
"""计算宝石成本"""
@abstractmethod
def calculate_gem_recycle_price(self) -> float:
"""新增:计算宝石回收残值"""
这种接口设计确保了:
以黄金材质为例,我们实现GoldMaterialImpl:
python复制class GoldMaterialImpl(JewelryMaterialImpl):
def calculate_material_cost(self, weight: float) -> float:
"""黄金成本 = 克重 × 单价"""
return self.entity.cost_per_gram * weight
def check_purity(self, actual_purity: float) -> bool:
"""检查纯度是否达标"""
return actual_purity >= self.entity.purity_standard
def calculate_material_recycle_price(self, weight: float) -> float:
"""黄金回收价 = 成本 × 回收折价率"""
return self.calculate_material_cost(weight) * self.entity.recycle_ratio
关键点说明:
self.entity是被组合的材质实体钻石的实现稍有不同:
python复制class DiamondGemImpl(JewelryGemImpl):
def calculate_gem_cost(self) -> float:
"""钻石成本 = 克拉数 × 单价"""
return self.entity.carat * self.entity.unit_price
def calculate_gem_recycle_price(self) -> float:
"""钻石回收残值 = 成本 × 折价率"""
return self.calculate_gem_cost() * self.entity.gem_recycle_ratio
注意到:
业务基类JewelryBusiness组合了实体和实现:
python复制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:
"""执行业务流程"""
具体业务如销售流程:
python复制class SaleBusiness(JewelryBusiness):
def process(self) -> str:
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"销售完成,利润:{profit:.2f}元"
与传统业务不同,回收需要质检环节:
python复制class RecycleBusiness(JewelryBusiness):
def __init__(self, jewelry_entity: JewelryEntity,
material_impl: JewelryMaterialImpl,
gem_impl: JewelryGemImpl,
check_result: bool):
super().__init__(jewelry_entity, material_impl, gem_impl)
self.check_result = check_result
def process(self) -> str:
if not self.check_result:
return "质检不合格,拒绝回收"
material_price = self.material_impl.calculate_material_recycle_price(
self.entity.weight)
gem_price = self.gem_impl.calculate_gem_recycle_price()
return f"回收总价:{material_price + gem_price:.2f}元"
python复制# 创建足金999材质实体
gold = MaterialEntity(name="足金999", cost_per_gram=580.0,
purity_standard=99.9, recycle_ratio=0.95)
# 创建钻石实体
diamond = GemEntity(type="钻石", carat=1.2,
unit_price=80000.0, gem_recycle_ratio=0.6)
# 创建珠宝实体
ring = JewelryEntity(material=gold, gem=diamond,
weight=18.0, purity=99.95)
# 创建实现层实例
material_impl = GoldMaterialImpl(gold)
gem_impl = DiamondGemImpl(diamond)
# 执行业务流程
print(SaleBusiness(ring, material_impl, gem_impl).process())
print(RecycleBusiness(ring, material_impl, gem_impl, True).process())
Impl后缀能明确表示这是实现类虽然桥接模式增加了间接层,但合理实现下性能影响很小:
@staticmethod减少self访问__slots__减少内存占用为确保桥接模式的正确性,需要:
示例测试用例:
python复制def test_gold_cost_calculation():
gold = MaterialEntity(cost_per_gram=500, purity_standard=99.9)
impl = GoldMaterialImpl(gold)
assert impl.calculate_material_cost(10) == 5000
def test_diamond_recycle():
diamond = GemEntity(carat=1, unit_price=10000, gem_recycle_ratio=0.5)
impl = DiamondGemImpl(diamond)
assert impl.calculate_gem_recycle_price() == 5000
Python的动态特性允许我们实现更灵活的桥接:
python复制def make_recycle_impl(recycle_ratio):
"""动态创建回收实现类"""
class DynamicRecycleImpl(JewelryMaterialImpl):
def calculate_material_recycle_price(self, weight):
return self.calculate_material_cost(weight) * recycle_ratio
return DynamicRecycleImpl
# 使用
gold_impl = make_recycle_impl(0.9)(gold_entity)
这种技术适合配置驱动的场景,但会牺牲一定的可读性。
在实际珠宝系统开发中,可能需要:
最终我采用的完整项目结构如下:
code复制jewelry_system/
├── entities/ # 实体类
├── interfaces/ # 桥接接口
├── implementations/ # 具体实现
├── businesses/ # 业务流程
└── tests/ # 测试代码
这种结构清晰分离了不同关注点,使系统保持高度可维护性。当产品经理提出新增"珠宝抵押"业务需求时,我只需添加MortgageBusiness类和可能的新接口方法,而无需修改任何现有业务逻辑——这正是桥接模式的威力所在。