python 组合模式

组合模式将对象组合成树形结构表示, 使得使用者在操作单个对象和一组对象时具有一致性.
在使用时通常会生成一棵对象树, 叶子节点是对象, 其他节点为组合对象.
在调用组合对象时, 会迭代调用所有叶子节点对象的方法.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from abc import ABC, abstractmethod


class Worker(ABC):
"""工作者抽象类"""
def __init__(self, name):
self.name = name

@abstractmethod
def work(self):
pass


class Employee(Worker):
"""雇员类"""
def work(self):
print('Employee {} start to work'.format(self.name))


class Leader(Worker):
"""领导类"""
depth = 0
def __init__(self, name):
self.members = []
super(Leader, self).__init__(name)

def add_member(self, employee):
if employee not in self.members:
self.members.append(employee)

def remove_member(self, employee):
if employee in self.members:
self.members.remove(employee)

def work(self):
print('Leader {} start to work'.format(self.name))
Leader.depth += 1
for employee in self.members:
print(' ' * Leader.depth, end='')
employee.work()

if __name__ == "__main__":
e1 = Employee('employee 1')
e2 = Employee('employee 2')
l1 = Leader('Leader 1')
l1.add_member(e1)
l1.add_member(e2)

e3 = Employee('employee 3')
l2 = Leader('Leader 2')
l2.add_member(e3)
l2.add_member(l1)

l2.work()

运行:

1
2
3
4
5
Leader Leader 2 start to work
Employee employee 3 start to work
Leader Leader 1 start to work
Employee employee 1 start to work
Employee employee 2 start to work