组合模式
本篇文章是通过看视频学习总结的内容, 如有错误的地方请谅解,并联系博主及时修改,谢谢您的阅读.
何为组合模式?
也被称为整体——部分模式,不管是整体还是部分,最终都是通过一个方法来操作
适用场景:
部分——整体场景,树形菜单,文件、文件夹的管理
组合模式的优点:
- 客户端调用简单
- 节点数量自由控制
组合模式的缺点:
- 组合模式中,并不是面向得接口编程,而是面向抽象类编程
- 如果采用透明写法来实现,那么不满足最少知道原则
- 如果采用安全写法,那么不存在最少知道原则
举个例子(Linux文件系统在组合模式中得安全写法):
- 顶层抽象
/**
* <p>
* Linux 系统目录,顶层抽象
* </p>
*
* @author zyred
* @createTime 2020/9/9 14:03
**/
public abstract class Directory {
protected String name;
public Directory(String name) {
this.name = name;
}
/** 方法抽象,展示 **/
public abstract void show();
}
- 父级节点
/**
* <p>
* Linux 文件夹 - 根节点
* 这里得方法被定义在了Folder 类中,并没有定义在 Directory 中,这样叶子节点满足最少知道原则
* </p>
*
* @author zyred
* @createTime 2020/9/9 14:15
**/
public class Folder extends Directory {
/** 目录等级 **/
private Integer level;
/** 子集 **/
private List<Directory> dirs;
public Folder(String name, int level) {
super(name);
this.level = level;
this.dirs = new ArrayList<>();
}
@Override
public void show() {
System.out.println(this.name);
for (Directory dir : dirs) {
if (this.level != null) {
for (Integer i = 0; i < this.level; i++) {
System.out.print(" ");
}
for (Integer i = 0; i < this.level; i++) {
if (i == 0) {
System.out.print("+");
}
System.out.print("-");
}
}
dir.show();
}
}
public Folder add(Directory dir) {
this.dirs.add(dir);
return this;
}
public void remove(Directory dir) {
this.dirs.remove(dir);
}
public Directory get(int index) {
return this.dirs.get(index);
}
}
- 叶子节点
/**
* <p>
* Linux文件 - 叶子节点
* </p>
*
* @author zyred
* @createTime 2020/9/9 14:13
**/
public class File extends Directory{
public File(String name) {
super(name);
}
@Override
public void show() {
System.out.println(this.name);
}
}
- 客户端
public class SafeCompositeClient {
public static void main(String[] args) {
File qq = new File("QQ");
File wechat = new File("wechat");
Folder tencent = new Folder("Tencent", 2).add(qq).add(wechat);
File ppt = new File("ppt");
File word = new File("word");
File excel = new File("excel");
Folder office = new Folder("office", 2).add(ppt).add(word).add(excel);
Folder linux = new Folder("Linux", 1).add(tencent).add(office);
linux.show();
}
}
- 输出结果
Linux
+-Tencent
+--QQ
+--wechat
+-office
+--ppt
+--word
+--excel
总结:
- 使用组合模式来完成对树形结构的处理,让客户端在处理的时候,变得更加的清晰,更加的灵活