組合模式主要是為了表達(dá)“部分-整體”的層次結(jié)構(gòu),例如公司的組織架構(gòu),每個(gè)部門下又有若干個(gè)下級(jí)部門,再如菜單結(jié)構(gòu),每個(gè)菜單下可能有一個(gè)或多個(gè)子菜單。
下例以員工的層級(jí)結(jié)構(gòu)說(shuō)明組合模式的用法。每個(gè)員工都有姓名、部門、工資等屬性,每個(gè)員工可能有0個(gè)或多個(gè)下屬員工。
Employee類的代碼如下:
package composite;
import java.util.ArrayList;
import java.util.List;
public class Employee {
private String name;
private String department;
private int salary;
private List < Employee > subordinates;
//構(gòu)造函數(shù)
public Employee(String name, String department, int salary) {
this.name=name;
this.department=department;
this.salary=salary;
this.subordinates=new ArrayList < Employee > ();
}
//添加下屬
public void add(Employee employee) {
subordinates.add(employee);
}
//移除下屬
public void remove(Employee employee) {
subordinates.remove(employee);
}
//獲取下屬
public List < Employee > getSubordinates(){
return subordinates;
}
//轉(zhuǎn)成字符串
public String toString() {
return "員工(姓名:"+name+",部門:"+department+",工資:"+salary+")";
}
}
主函數(shù)調(diào)用方式:
package main;
import composite.*;
public class CompositePattern {
public static void main(String[] args) {
//創(chuàng)建一個(gè)員工:總裁
Employee president = new Employee("李剛","管理層",30000);
//創(chuàng)建兩個(gè)員工:部門領(lǐng)導(dǎo)
Employee directorSales = new Employee("王孟","銷售部",20000);
Employee directorRND = new Employee("嚴(yán)明","研發(fā)部",20000);
//創(chuàng)建兩個(gè)員工:銷售部銷售員
Employee saler1 = new Employee("孟德貴","銷售部",10000);
Employee saler2 = new Employee("肖亮高","銷售部",10000);
//創(chuàng)建兩個(gè)員工:研發(fā)部工程師
Employee engineer1 = new Employee("左弓成","研發(fā)部",10000);
Employee engineer2 = new Employee("成顏發(fā)","研發(fā)部",10000);
//總裁添加下屬
president.add(directorSales);
president.add(directorRND);
//銷售部部門領(lǐng)導(dǎo)添加下屬
directorSales.add(saler1);
directorSales.add(saler2);
//研發(fā)部部門領(lǐng)導(dǎo)添加下屬
directorRND.add(engineer1);
directorRND.add(engineer2);
//打印輸出所有員工
System.out.println(president);
for(Employee directorEmployee: president.getSubordinates()) {
System.out.println(directorEmployee);
for(Employee employee: directorEmployee.getSubordinates()) {
System.out.println(employee);
}
}
}
}
-
JAVA
+關(guān)注
關(guān)注
19文章
2972瀏覽量
104859 -
JAVA語(yǔ)言
+關(guān)注
關(guān)注
0文章
138瀏覽量
20113
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論