📅  最后修改于: 2023-12-03 15:10:42.233000             🧑  作者: Mango
构图模式是一种设计模式,它主要关注如何把对象组合成复杂的结构,使得这些对象可以同时被操作和管理。
构图模式又称为组合模式,它可以让你将对象组合成树形结构来表现”部分-整体“的层次结构。构图模式使得客户端以一致的方式处理单个对象以及对象的组合。
构图模式中主要有三种角色:
以下是以公司组织架构为例子的构图模式实现。
from abc import ABC, abstractmethod
class Component(ABC):
@abstractmethod
def show(self, indent):
pass
class Employee(Component):
def __init__(self, name, position, salary):
self.name = name
self.position = position
self.salary = salary
def show(self, indent):
print(f'{indent}- {self.name}, {self.position}, {self.salary}')
class Department(Component):
def __init__(self, name, employees=None):
self.name = name
self.employees = employees or []
def add_employee(self, employee):
self.employees.append(employee)
def remove_employee(self, employee):
self.employees.remove(employee)
def show(self, indent=''):
print(f'{indent}Department: {self.name}')
for employee in self.employees:
employee.show(indent + '\t')
if __name__ == "__main__":
hr_department = Department('HR')
hr_department.add_employee(Employee('John', 'HR manager', 10000))
hr_department.add_employee(Employee('Mary', 'HR assistant', 3000))
rd_department = Department('R&D')
rd_department.add_employee(Employee('Bob', 'Software engineer', 5000))
rd_department.add_employee(Employee('Alice', 'Product manager', 8000))
company = Department('Company')
company.add_employee(hr_department)
company.add_employee(rd_department)
company.show()
输出:
Department: Company
Department: HR
- John, HR manager, 10000
- Mary, HR assistant, 3000
Department: R&D
- Bob, Software engineer, 5000
- Alice, Product manager, 8000
构图模式让我们以一致的方式处理单个对象以及对象的组合,它可以让我们建立一颗对象树,将对象组合成复杂的结构,从而使得这些对象可以同时被操作和管理。