如上图所示,在院系、大学类中都存在一个List,则department、university泛化origination的同时,也将origination聚合到自己本身。
package com.design.composite;
/**
* 所有机构的抽象类
* @author Fighting
*
*/
public abstract class Origination {
private String name;
private String desc;
public Origination(String name, String desc) {
this.name = name;
this.desc = desc;
}
protected void add(Origination origination){}
protected void remove(Origination origination){}
protected void print(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
package com.design.composite;
import java.util.ArrayList;
import java.util.List;
/**
* 大学
* @author Fighting
*
*/
public class University extends Origination{
public University(String name, String desc) {
super(name, desc);
}
private List<Origination> departmentList = new ArrayList<>();
protected void add(Origination origination) {
departmentList.add(origination);
}
@Override
protected void remove(Origination origination) {
departmentList.remove(origination);
}
@Override
protected void print() {
System.out.println("------["+super.getName()+"]-----");
for (Origination origination : departmentList) {
System.out.println(origination.getName());
}
}
}
package com.design.composite;
import java.util.ArrayList;
import java.util.List;
/**
* 院系
*
* @author Fighting
*
*/
public class Department extends Origination {
public Department(String name, String desc) {
super(name, desc);
}
private List<Origination> maojorList = new ArrayList<>();
protected void add(Origination origination) {
maojorList.add(origination);
}
@Override
protected void remove(Origination origination) {
maojorList.remove(origination);
}
@Override
protected void print() {
System.out.println("------["+super.getName()+"]-----");
for (Origination origination : maojorList) {
System.out.println(origination.getName());
}
}
}
package com.design.composite;
/**
* 专业
* @author Fighting
*
*/
public class Major extends Origination {
public Major(String name, String desc) {
super(name, desc);
}
@Override
protected void print() {
System.out.println("------["+super.getName()+"]-----");
}
}
package com.design.composite;
public class Client {
public static void main(String[] args) {
Origination university = new University("清华大学", "一流大学");
Origination computerDepartment = new Department("计算机学院", "very nice");
Department infoDepartment = new Department("信息学院", "very greet");
Major code = new Major("软件开发与测试", "非常哭");
Major vision = new Major("自媒体专业","非常高大上");
computerDepartment.add(code);
computerDepartment.add(vision);
university.add(computerDepartment);
university.add(infoDepartment);
university.print();
computerDepartment.print();
}
}