使用場(chǎng)景:部分兑宇、整體場(chǎng)景,如樹(shù)形菜單粱坤,文件隶糕、文件夾的管理。
以公司員工組織架構(gòu)為例
[圖片上傳失敗...(image-818266-1632387191971)]
- 步驟一: 創(chuàng)建 Employee 類(lèi)站玄,該類(lèi)帶有 Employee 對(duì)象的列表枚驻。
public class Employee {
private String name;
private String dept;
private int salary;
private List<Employee> subordinates;//下級(jí)
public Employee(String name, String dept, int salary){
this.name = name;
this.dept = dept;
this.salary = salary;
this.subordinates = new ArrayList<>();
}
public void add(Employee e){
subordinates.add(e);
}
public void remove(Employee e) {
subordinates.remove(e);
}
public List<Employee> getSubordinates(){
return subordinates;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", dept='" + dept + '\'' +
", salary=" + salary +
'}';
}
}
- 步驟二: 創(chuàng)建 Employee 類(lèi),該類(lèi)帶有 Employee 對(duì)象的列表蜒什。
public class CompositePatternDemo {
public static void main(String[] args) {
Employee ceo = new Employee("name1", "CEO", 100000);
Employee headSales = new Employee("name11", "Head Sales", 30000);
Employee headMarketing = new Employee("name12", "Head Marketing", 30000);
Employee sale1 = new Employee("name111", "Sales", 10000);
Employee sale2 = new Employee("name112", "Sales", 10000);
Employee clerk1 = new Employee("name121", "Marketing", 10000);
Employee clerk2 = new Employee("name122", "Marketing", 10000);
ceo.add(headSales);
ceo.add(headMarketing);
headSales.add(sale1);
headSales.add(sale2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
//打印該組織的所有員工
System.out.println(ceo);
for (Employee sub : ceo.getSubordinates()) {
System.out.println(sub);
for (Employee sub2 : sub.getSubordinates()) {
System.out.println(sub2);
}
}
}
}
結(jié)果:
Employee{name='name1', dept='CEO', salary=100000}
Employee{name='name11', dept='Head Sales', salary=30000}
Employee{name='name111', dept='Sales', salary=10000}
Employee{name='name112', dept='Sales', salary=10000}
Employee{name='name12', dept='Head Marketing', salary=30000}
Employee{name='name121', dept='Marketing', salary=10000}
Employee{name='name122', dept='Marketing', salary=10000}