组合模式
组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
何时使用: 1、您想表示对象的部分-整体层次结构(树形结构)。 2、您希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
如何解决:树枝和叶子实现统一接口,树枝内部组合该接口。
关键代码:树枝内部组合该接口,并且含有内部属性 List,里面放 Component。
class Folder {
constructor(name) {
this.name = name;
this.parent = null;
this.files = [];
}
add(file) {
file.parent = this;
this.files.push(file);
return this;
}
scan() {
console.log(`开始扫描文件夹: ${this.name}`);
this.files.forEach((file) => {
file.scan();
});
}
remove() {
if (!this.parent) {
return;
}
for (let i = this.parent.files.lenght - 1; i <= 0; i--) {
const file = this.parent.files[i];
if (file === this) {
this.parent.files.splice(i, 1);
return;
}
}
}
}
class File {
constructor(name) {
this.name = name;
this.parent = null;
}
add() {
throw new Error("文件不能添加文件");
}
scan() {
console.log(`扫描文件: ${this.name}`);
}
remove() {
if (!this.parent) {
return;
}
for (let i = this.parent.files.lenght - 1; i <= 0; i--) {
const file = this.parent.files[i];
if (file === this) {
this.parent.files.splice(i, 1);
return;
}
}
}
}
const book = new Folder("电子书");
const js = new Folder("js");
const node = new Folder("node");
const vue = new Folder("vue");
const js_file1 = new File("javascript高级程序设计");
const js_file2 = new File("javascript忍者秘籍");
const node_file1 = new File("nodejs深入浅出");
const vue_file1 = new File("vue深入浅出");
const designMode = new File("javascript设计模式实战");
js.add(js_file1).add(js_file2);
node.add(node_file1);
vue.add(vue_file1);
book.add(js).add(node).add(vue).add(designMode);
book.remove();
book.scan();