1
0
Fork 0
design-patterns/python/composite/main.py

75 lines
1.9 KiB
Python

"""
实例
汤宝宝成为了上市集团老总,他们集团有好多好多家分公司...
"""
from abc import ABC, abstractmethod
# 接口
class component(ABC):
name: str
@abstractmethod
def show(self, prefix: str) -> None:
pass
# 具体类
class Department(component):
name: str
def __init__(self, name: str) -> None:
self.name = name
def show(self, prefix: str) -> None:
print(f"{prefix}{self.name}")
# 实现类
class Company(component):
name: str
children: list[component]
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: component) -> None:
self.children.append(company)
print(f"{self.name}下开设了{company.name}")
def remove(self, company: component) -> None:
self.children.remove(company)
print(f"{self.name}下裁撤了{company.name}")
def get_child(self, index: int) -> component:
if index < 0 or index >= len(self.children):
raise IndexError("子公司索引超出范围")
return self.children[index]
if __name__ == "__main__":
print("============= 组合模式 =============")
head_office = Company("汤氏总公司")
head_office.add(Company("汤氏A分公司"))
head_office.add(Department("人事部"))
head_office.add(Department("研发部"))
child = head_office.get_child(0)
if isinstance(child, Company):
child.add(Department("市场部"))
child.add(Department("财务部"))
head_office.remove(head_office.get_child(2))
print("\n")
head_office.show("~ ")
print("\n")
head_office.get_child(0).show("~ ")
print("\n=========== 组合模式结束 ===========")