组合模式,就是在一个对象中包含其他对象,这些被包含的对象可能是终点对象(不再包含别的对象),也有可能是非终点对象(其内部还包含其他对象,或叫组对象),我们将对象称为节点,即一个根节点包含许多子节点,这些子节点有的不再包含子节点,而有的仍然包含子节点,以此类推。
2、所谓组合模式,其实说的是对象包含对象的问题,通过组合的方式(在对象内部引用对象)来进行布局,我认为这种组合是区别于继承的,而另一层含义是指树形结构子节点的抽象(将叶子节点与数枝节点抽象为子节点),区别于普通的分别定义叶子节点与数枝节点的方式。
public class Employee {
private String name;
private String dept;
private int salary;
private List<Employee> subordinates;
public Employee(String name, String dept, int salar) {
this.name = name;
this.dept = dept;
this.salary = salary;
subordinates=new ArrayList<Employee>();
}
public String getName() {
return name;
}
public void add(Employee e){
subordinates.add(e);
}
public void remove(Employee e){
subordinates.remove(e);
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", dept='" + dept + '\'' +
", salary=" + salary +
", subordinates=" + subordinates +
'}';
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public List<Employee> getSubordinates() {
return subordinates;
}
public void setSubordinates(List<Employee> subordinates) {
this.subordinates = subordinates;
}
}
public class CompositePatternDemo {
public static void main(String[] args){
Employee CEO=new Employee("John","CEO",3000);
Employee headSales=new Employee("Robert","CEO",3000);
Employee headMarketing=new Employee("Michel","CEO",3000);
Employee clerk1=new Employee("Laura","CEO",3000);
Employee clerk2=new Employee("Bob","CEO",3000);
Employee salesExecutive1=new Employee("Richard","CEO",3000);
Employee salesExecutive2=new Employee("Rob","CEO",3000);
CEO.add(headSales);
CEO.add(headMarketing);
headSales.add(salesExecutive1);
headSales.add(salesExecutive2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
System.out.println(CEO);
for(Employee headEmployee:CEO.getSubordinates()){
System.out.println(headEmployee);
for(Employee employee:headEmployee.getSubordinates()){
System.out.println(employee);
}
}
}
}