JavaScript-组合模式

组合模式

组合模式(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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值