本人为菜鸟,仅供参考,只为自己记录学习
作用
运用于树形结构中,使复杂元素的内部结构解耦
优点
高层模块调用简单、节点自由添加
缺点
都是实现类,违法了依赖倒置原则
使用场景
部分、整体场景,如树形菜单,文件、文件夹的管理
员工类
@AllArgsConstructor
@Data
@ToString
public class Employee {
private String name;
private String dept;
private int salary;
private List<Employee> subordinates;
public void add(Employee employee) {
subordinates.add(employee);
}
public void remove(Employee employee) {
subordinates.remove(employee);
}
}
测试类
public class CompositeTest {
public static void main(String[] args) {
Employee luo = new Employee("小罗", "develop", 3000, null);
Employee he = new Employee("老贺", "develop", 5000, null);
Employee wa = new Employee("老王", "develop", 4500, null);
List<Employee> huList = new ArrayList<>();
huList.add(luo);
Employee hu = new Employee("老胡", "master develop", 14000, huList);
List<Employee> yueList = new ArrayList<>();
yueList.add(he);
yueList.add(wa);
Employee yue = new Employee("老岳", "master develop", 12000, yueList);
List<Employee> shenList = new ArrayList<>();
shenList.add(hu);
shenList.add(yue);
Employee shen = new Employee("沈总", "CEO", 30000, shenList);
System.out.println(shen);
}
}
打印结果
Employee(name=沈总, dept=CEO, salary=30000, subordinates=[Employee(name=老胡, dept=master develop, salary=14000, subordinates=[Employee(name=小罗, dept=develop, salary=3000, subordinates=null)]), Employee(name=老岳, dept=master develop, salary=12000, subordinates=[Employee(name=老贺, dept=develop, salary=5000, subordinates=null), Employee(name=老王, dept=develop, salary=4500, subordinates=null)])])