用于把一组相似的对象当成一个对象来使用
使用场景
- ceo > manager > employee
- 文件夹与文件,属性菜单
Demo
"""组合模式"""class Employee:def __init__(self, name, age):self.name = nameself.age = ageself.subordinates = []def add(self, e):self.subordinates.append(e)def remove(self, e):self.subordinates.remove(e)def display(self):for subordinate in self.subordinates:print(f'my name is {subordinate.name}, age is {subordinate.age}')if subordinate.subordinates:subordinate.display()if __name__ == '__main__':ceo = Employee('ceo', 22)m1 = Employee('m1', 20)m2 = Employee('m2', 23)ceo.add(m1)ceo.add(m2)e1 = Employee('e1', 18)m1.add(e1)ceo.display()
