电子说
组合模式主要是为了表达“部分-整体”的层次结构,例如公司的组织架构,每个部门下又有若干个下级部门,再如菜单结构,每个菜单下可能有一个或多个子菜单。
下例以员工的层级结构说明组合模式的用法。每个员工都有姓名、部门、工资等属性,每个员工可能有0个或多个下属员工。
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;
//构造函数
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;
}
//转成字符串
public String toString() {
return "员工(姓名:"+name+",部门:"+department+",工资:"+salary+")";
}
}
主函数调用方式:
package main;
import composite.*;
public class CompositePattern {
public static void main(String[] args) {
//创建一个员工:总裁
Employee president = new Employee("李刚","管理层",30000);
//创建两个员工:部门领导
Employee directorSales = new Employee("王孟","销售部",20000);
Employee directorRND = new Employee("严明","研发部",20000);
//创建两个员工:销售部销售员
Employee saler1 = new Employee("孟德贵","销售部",10000);
Employee saler2 = new Employee("肖亮高","销售部",10000);
//创建两个员工:研发部工程师
Employee engineer1 = new Employee("左弓成","研发部",10000);
Employee engineer2 = new Employee("成颜发","研发部",10000);
//总裁添加下属
president.add(directorSales);
president.add(directorRND);
//销售部部门领导添加下属
directorSales.add(saler1);
directorSales.add(saler2);
//研发部部门领导添加下属
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);
}
}
}
}
全部0条评论
快来发表一下你的评论吧 !