实现桥接模式和组合模式示例,添加相关类和方法,增强代码可读性

This commit is contained in:
2025-12-31 17:40:38 +08:00
parent 64cc579e42
commit 86497cc06b
6 changed files with 406 additions and 0 deletions
+67
View File
@@ -0,0 +1,67 @@
"""
实例
汤宝宝成为了一个电子画家,但是不同形状的笔刷和不同颜色颜料的组合让他犯了难...
"""
from abc import ABC, abstractmethod
# 抽象类
class Paint(ABC):
@abstractmethod
def use(self) -> str:
pass
class Brush(ABC):
@abstractmethod
def draw(self) -> None:
pass
# 具体实现类
class RedPaint(Paint):
def use(self) -> str:
return "红色颜料"
class BluePaint(Paint):
def use(self) -> str:
return "蓝色颜料"
class RoundBrush(Brush):
def __init__(self, paint: Paint) -> None:
super().__init__()
self.paint = paint
def draw(self) -> None:
print("使用圆形笔刷和" + self.paint.use() + "进行绘图!")
class SquareBrush(Brush):
def __init__(self, paint: Paint) -> None:
super().__init__()
self.paint = paint
def draw(self) -> None:
print("使用方形笔刷和" + self.paint.use() + "进行绘图!")
# 绘图函数
def painting(brush: Brush) -> None:
brush.draw()
if __name__ == "__main__":
print("============= 桥接模式 =============")
red_paint = RedPaint()
blue_paint = BluePaint()
painting(RoundBrush(red_paint))
painting(SquareBrush(red_paint))
painting(RoundBrush(blue_paint))
painting(SquareBrush(blue_paint))
print("\n=========== 桥接模式结束 ===========")
+73
View File
@@ -0,0 +1,73 @@
"""
实例
汤宝宝成为了上市集团老总,他们集团有好多好多家分公司...
"""
from abc import ABC, abstractmethod
# 抽象类
class Company(ABC):
name: str
children: list["Company"]
@abstractmethod
def show(self, prefix: str) -> None:
pass
@abstractmethod
def add(self, company: "Company") -> None:
pass
@abstractmethod
def remove(self, company: "Company") -> None:
pass
@abstractmethod
def get_child(self, index: int) -> "Company":
pass
# 实现类
class ConcreteCompany(Company):
name: str
children: list[Company]
def __init__(self, name: str) -> None:
self.name = name
self.children = []
def show(self, prefix: str) -> None:
print(f"{prefix}{self.name}")
for child in self.children:
child.show(f"{prefix}-> ")
def add(self, company: Company) -> None:
self.children.append(company)
print(f"在{self.name}下开设了分公司{company.name}")
def remove(self, company: Company) -> None:
self.children.remove(company)
print(f"在{self.name}下关闭了分公司{company.name}")
def get_child(self, index: int) -> Company:
if index < 0 or index >= len(self.children):
raise IndexError("子公司索引超出范围")
return self.children[index]
if __name__ == "__main__":
print("============= 组合模式 =============")
head_office = ConcreteCompany("汤氏总公司")
head_office.add(ConcreteCompany("汤氏A分公司"))
head_office.add(ConcreteCompany("汤氏B分公司"))
head_office.add(ConcreteCompany("汤氏C分公司"))
head_office.get_child(0).add(ConcreteCompany("汤氏A分公司-子公司1"))
head_office.get_child(0).add(ConcreteCompany("汤氏A分公司-子公司2"))
head_office.remove(head_office.get_child(2))
print("\n")
head_office.show("~ ")
print("\n")
head_office.get_child(0).show("~ ")
print("\n=========== 组合模式结束 ===========")