一、简介
组合(Composite Pattern)模式的定义:有时又叫作整体-部分(Part-Whole)模式,它是一种将对象组合成树状的层次结构的模式,用来表示“整体-部分”的关系,使用户对单个对象和组合对象具有一致的访问性,属于结构型设计模式。
在组合模式中,整个树形结构中的对象都属于同一种类型,带来的好处就是用户不需要辨别是树枝节点还是叶子节点,可以直接进行操作,给用户的使用带来极大的便利。
二、优缺点
优点:
- 组合模式使得客户端代码可以一致地处理单个对象和组合对象,无须关心自己处理的是单个对象,还是组合对象,这简化了客户端代码;
- 更容易在组合体内加入新的对象,客户端不会因为加入了新的对象而更改源代码,满足“开闭原则”;
缺点:
- 设计较复杂,客户端需要花更多时间理清类之间的层次关系;
- 不容易限制容器中的构件;
- 不容易用继承的方法来增加构件的新功能;
三、应用场景
1) 系统中存在大量相同或相似的对象,这些对象耗费大量的内存资源。
2) 大部分的对象可以按照内部状态进行分组,且可将不同部分外部化,这样每一个组只需保存一个内部状态。
3) 由于享元模式需要额外维护一个保存享元的数据结构,所以应当在有足够多的享元实例时才值得使用享元模式。
四、模式结构
1. 主要角色
- 抽象构件(Component)角色:它的主要作用是为树叶构件和树枝构件声明公共接口,并实现它们的默认行为。在透明式的组合模式中抽象构件还声明访问和管理子类的接口;在安全式的组合模式中不声明访问和管理子类的接口,管理工作由树枝构件完成。(总的抽象类或接口,定义一些通用的方法,比如新增、删除)
- 树叶构件(Leaf)角色:是组合中的叶节点对象,它没有子节点,用于继承或实现抽象构件。
- 树枝构件(Composite)角色 / 中间构件:是组合中的分支节点对象,它有子节点,用于继承和实现抽象构件。它的主要作用是存储和管理子部件,通常包含 Add()、Remove()、GetChild() 等方法。
2. UML类图
五、代码实现
- 抽象构件
public abstract class Course {
public String getName() throws Exception {
throw new Exception("不支持获取课程名!");
}
public void addChild(Course c) throws Exception{
throw new Exception("不支持创建子项!");
}
public abstract void info();
}
- 树枝构件
public class LevelCourse extends Course {
private List<Course> courseList = new ArrayList<>();
private String name;
private int level;
public LevelCourse(String name, int level) {
this.name = name;
this.level = level;
}
@Override
public String getName() throws Exception {
return this.name;
}
@Override
public void addChild(Course c) throws Exception {
courseList.add(c);
}
@Override
public void info() {
System.out.println("课程:" + this.name);
for(Course course : courseList){
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.print(">");
course.info();
}
}
}
- 树叶构建
public class CommonCourse extends Course {
private String name;
private double score;
public CommonCourse(String name, double score) {
this.name = name;
this.score = score;
}
@Override
public String getName() {
return this.name;
}
@Override
public void info() {
System.out.println("课程:" + this.name + ",分数:" + this.score);
}
}
- 测试
@Test
public void test() throws Exception{
Course ywCourse = new CommonCourse("语文", 150);
Course sxCourse = new CommonCourse("数学", 150);
Course yyCourse = new CommonCourse("英语", 150);
Course wlCourse = new CommonCourse("物理", 100);
Course hxCourse = new CommonCourse("化学", 100);
Course swCourse = new CommonCourse("生物", 100);
Course lz = new LevelCourse("理综", 2);
lz.addChild(wlCourse);
lz.addChild(hxCourse);
lz.addChild(swCourse);
Course course = new LevelCourse("高考科目", 1);
course.addChild(ywCourse);
course.addChild(sxCourse);
course.addChild(yyCourse);
course.addChild(lz);
course.info();
}