重构组合模式示例,统一接口定义,增强代码可读性和一致性

This commit is contained in:
2025-12-31 18:33:24 +08:00
parent 86497cc06b
commit 9b51101c27
3 changed files with 92 additions and 73 deletions
+30 -29
View File
@@ -6,32 +6,31 @@
from abc import ABC, abstractmethod
# 抽象类
class Company(ABC):
# 接口
class component(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):
# 具体类
class Department(component):
name: str
children: list[Company]
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
@@ -42,15 +41,15 @@ class ConcreteCompany(Company):
for child in self.children:
child.show(f"{prefix}-> ")
def add(self, company: Company) -> None:
def add(self, company: component) -> None:
self.children.append(company)
print(f"在{self.name}下开设了分公司{company.name}")
print(f"在{self.name}下开设了{company.name}")
def remove(self, company: Company) -> None:
def remove(self, company: component) -> None:
self.children.remove(company)
print(f"在{self.name}下关闭了分公司{company.name}")
print(f"在{self.name}下裁撤了{company.name}")
def get_child(self, index: int) -> Company:
def get_child(self, index: int) -> component:
if index < 0 or index >= len(self.children):
raise IndexError("子公司索引超出范围")
return self.children[index]
@@ -59,12 +58,14 @@ class ConcreteCompany(Company):
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 = 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("~ ")