23种设计模式之组合模式
模式结构
- 抽象构件(Component)角色:它的主要作用是为树叶构件和树枝构件声明公共接口,并实现它们的默认行为。在透明式的组合模式中抽象构件还声明访问和管理子类的接口;在安全式的组合模式中不声明访问和管理子类的接口,管理工作由树枝构件完成。(总的抽象类或接口,定义一些通用的方法,比如新增、删除)
- 树叶构件(Leaf)角色:是组合中的叶节点对象,它没有子节点,用于继承或实现抽象构件。
- 树枝构件(Composite)角色 / 中间构件:是组合中的分支节点对象,它有子节点,用于继承和实现抽象构件。它的主要作用是存储和管理子部件,通常包含 Add()、Remove()、GetChild() 等方法。
案例
public interface School {
public void addPart(School school);
public void removePart(School school);
public void displayPart();
public void action();
}
public class ConcreteSchool implements School {
private String name;
private List<School> partList = new ArrayList<>();
public ConcreteSchool(String name){
this.name = name;
}
@Override
public void addPart(School school) {
partList.add(school);
}
@Override
public void removePart(School school) {
partList.remove(school);
}
@Override
public void displayPart() {
for (int i = 0; i < partList.size(); i++) {
School school = partList.get(i);
school.displayPart();
}
}
@Override
public void action() {
for (int i = 0; i < partList.size(); i++) {
School school = partList.get(i);
school.action();
}
}
}
public class InternetDepartmentSchool implements School{
private String name;
public InternetDepartmentSchool(String name){
this.name = name;
}
@Override
public void addPart(School school) {
}
@Override
public void removePart(School school) {
}
@Override
public void displayPart() {
}
@Override
public void action() {
System.out.println("我是:" + name);
}
}
public class SecurityDepartmentSchool implements School {
private String name;
public SecurityDepartmentSchool(String name){
this.name = name;
}
@Override
public void addPart(School school) {
}
@Override
public void removePart(School school) {
}
@Override
public void displayPart() {
}
@Override
public void action() {
System.out.println("我是:" + name);
}
}
public class CompositeTest {
public static void main(String[] args) {
School school = new ConcreteSchool("总校");
school.addPart(new InternetDepartmentSchool("网路部门"));
school.addPart(new SecurityDepartmentSchool("安全部门"));
school.displayPart();
school.action();
}
}