0%

设计模式-组合模式

组合模式(Composite pattern),属于结构型模式,将对象组合成为树状结构,可以像单独对象一样处理树状结构。

结构


涉及到了三个角色,Component(组件)、Leaf(叶子结点)、Composite(组合)

组件

Component,组件接口包含树中所有元素的公共操作,示例如下

1
2
3
public interface Department {
void printDepartmentName();
}

叶子结点

Leaf,组件接口方法的实现,也是真正完成工作的结点,即不包括对其他结点的引用。示例如下

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
public class FinancialDepartment implements Department{
private int id;
private String name;
public FinancialDepartment(int id, String name){
this.id = id;
this.name = name;
}
@Override
public void printDepartmentName() {
System.out.println(id + " " + name);
}
}

public class SalesDepartment implements Department {
private int id;
private String name;
public SalesDepartment(int id, String name){
this.id = id;
this.name = name;
}
@Override
public void printDepartmentName() {
System.out.println(id + " " + name);
}
}

组合

Composite,实现组件接口方法,并可以对元素进行管理。示例如下

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
public class ManagerDepartment implements Department{
private int id;
private String name;
private List<Department> childDepartments;
public ManagerDepartment(int id, String name){
this.id = id;
this.name = name;
this.childDepartments = new ArrayList<>();
}
@Override
public void printDepartmentName() {
childDepartments.forEach(Department::printDepartmentName);
}
public void addDepartment(Department department) {
childDepartments.add(department);
}

public void removeDepartment(Department department) {
childDepartments.remove(department);
}

public List<Department> getChild()
{
return childDepartments;
}
}

JDK1.8后引入forEach方法
before:

1
2
3
for(Department department : childDepartments){
department.printDepartmentName();
}

after:

1
childDepartments.forEach(Department::printDepartmentName);

客户端

对上述代码测试,示例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Client {
public static void main(String[] args) {
ManagerDepartment root = new ManagerDepartment(0, "北京总公司");
root.addDepartment(new SalesDepartment(1, "北京销售部"));
root.addDepartment(new FinancialDepartment(2, "北京财务部"));

ManagerDepartment shanghai = new ManagerDepartment(0, "上海分公司");
shanghai.addDepartment(new SalesDepartment(1, "上海销售部"));
shanghai.addDepartment(new FinancialDepartment(2, "上海财务部"));
root.addDepartment(shanghai);

ManagerDepartment xian = new ManagerDepartment(0, "西安分公司");
xian.addDepartment(new SalesDepartment(1, "西安销售部"));
xian.addDepartment(new FinancialDepartment(2, "西安财务部"));
root.addDepartment(xian);

root.printDepartmentName();
}
}

完整代码

完整代码已上传,项目地址https://github.com/yuan0824/DesignPattern

参考资料