组合模式是一种结构型的设计模式。组合模式中,对象具有一个List,用于保存其他的同类对象,从而形成了一个树形的结构,表示整体与部分的关系。在树形结构中,枝干节点和叶子节点会实现相同的接口(或者就是同一个类),从而在外部使用该对象时候,无需关注树形结构内部的细节,而可以统一的进行调用。
组合模式的使用场景,就是当出现树形结构,而且不需要关注复杂对象内部细节,只需要把复杂对象当作单一对象处理的时候。具体场景例如,二级部门是一级部门的子部门,挂靠在其下;操作系统中,文件是存放在对应的目录下,而目录其实也是一种文件。
2、案例 2.1、背景以上文中提到的部门情况为例。一级部门下边还存在多个二级部门,而所有的这些部门,都具有各自的一些信息,在主方法中来将部门的基本信息进行打印。我们的部门类,会包含本部门的某些特征信息,还会包含一个部门的集合,用户保存其负责的其他子部门。
2.2、实现1)部门类
import java.util.ArrayList;
import java.util.List;
public class Department
{
private String name;
private int numberOfPeople;
private String nameOfMinister;
private int level;
public List<Department> getSubDepartments() {
return subDepartments;
}
public void setSubDepartments(List<Department> subDepartments) {
this.subDepartments = subDepartments;
}
private List<Department> subDepartments;
public Department(String name, int numberOfPeople, String nameOfMinister, int level) {
this.name = name;
this.numberOfPeople = numberOfPeople;
this.nameOfMinister = nameOfMinister;
this.level = level;
this.subDepartments = new ArrayList<Department>();
}
public void add(Department department)
{
this.subDepartments.add(department);
}
public void remove(Department department)
{
this.subDepartments.remove(department);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfPeople() {
return numberOfPeople;
}
public void setNumberOfPeople(int numberOfPeople) {
this.numberOfPeople = numberOfPeople;
}
public String getNameOfMinister() {
return nameOfMinister;
}
public void setNameOfMinister(String nameOfMinister) {
this.nameOfMinister = nameOfMinister;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
2)验证
public class Test
{
public static void main(String[] args)
{
Department department_level1 = new Department("消费者BG",1000,
"zhang_san",1);
department_level1.add(new Department("产品线1",300,
"li_si",2));
department_level1.add(new Department("产品线2",300,
"wang_wu",2));
department_level1.add(new Department("产品线3",400,
"zhao_liu",2));
printDep(department_level1);
}
public static void printDep(Department department)
{
System.out.println("部门名称:" + department.getName());
System.out.println("部门人数:" + department.getNumberOfPeople());
System.out.println("部长名称:" + department.getNameOfMinister());
System.out.println("部门级别:" + department.getLevel());
System.out.println("--------------------------");
if (!department.getSubDepartments().isEmpty())
{
for (Department department1 : department.getSubDepartments())
{
printDep(department1);
}
}
}
}
3)运行结果
部门名称:消费者BG
部门人数:1000
部长名称:zhang_san
部门级别:1 部门名称:产品线1
部门人数:300
部长名称:li_si
部门级别:2 部门名称:产品线2
部门人数:300
部长名称:wang_wu
部门级别:2 部门名称:产品线3
部门人数:400
部长名称:zhao_liu
部门级别:2Process finished with exit code 0
3、总结
- 优点:复杂对象简单化,使用方便,易于进行节点的扩展