11、组合模式
**组合模式:**将对象组合成树形结构以表示“部分-整体”的层次结构。
应用场景:大学里有多个学院,每个学院有多个专业。
UML类图:
//抽象的组织类
public abstract class Organization {
protected String name;
public Organization(String name){
super();
this.name = name;
}
protected void add(Organization organization){
throw new UnsupportedOperationException();
}
protected void remove(Organization organization){
throw new UnsupportedOperationException();
}
protected abstract void print();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//大学类
public class University extends Organization {
List<Organization> organizationList = new ArrayList<>();
public University(String name) {
super(name);
}
@Override
protected void add(Organization organization) {
organizationList.add(organization);
}
@Override
protected void remove(Organization organization) {
organizationList.remove(organization);
}
@Override
protected void print() {
System.out.println("-------------" + getName() + "------------");
for (Organization organization : organizationList) {
organization.print();
}
}
}
//学院类
public class College extends Organization {
List<Organization> organizationList = new ArrayList<>();
public College(String name) {
super(name);
}
@Override
protected void add(Organization organization) {
organizationList.add(organization);
}
@Override
protected void remove(Organization organization) {
organizationList.remove(organization);
}
@Override
protected void print() {
System.out.println("-------------" + getName() + "------------");
for (Organization organization : organizationList) {
organization.print();
}
}
}
//专业类
public class Department extends Organization {
public Department(String name) {
super(name);
}
@Override
protected void print() {
System.out.println(getName());
}
}