JavaScript设计模式——组合模式

151 阅读1分钟

介绍

组合模式,又叫做整体-部分模式,它允许你将对象组合成树形结构来表现整体-部分层次结构,让使用者可以以一致的方式处理组合对象以及部分对象。

组合模式定义的包含组合对象和叶对象的层次结构,叶对象可以被组合成更复杂的组合对象,而这个组合对象又可以被组合,这样不断的组合下去。

js 代码

// 抽象组件
class Component {
  add(component) {}

  remove(component) {}

  getChild(i) {}

  operation() {}
}

// 叶子组件,代表没有子节点的节点
class Leaf extends Component {
  constructor(name) {
    super();
    this.name = name;
  }

  operation() {
    console.log(`Leaf ${this.name} 被调用`);
  }
}

// 复合组件,代表有子节点的节点
class Composite extends Component {
  constructor(name) {
    super();
    this.name = name;
    this.children = [];
  }

  add(component) {
    this.children.push(component);
  }

  remove(component) {
    const index = this.children.indexOf(component);
    if (index !== -1) {
      this.children.splice(index, 1);
    }
  }

  getChild(i) {
    return this.children[i];
  }

  operation() {
    console.log(`Composite ${this.name} 被调用`);
    this.children.forEach(child=>child.operation());
  }
}

// 使用组合模式构建对象树
const root = new Composite('root');
const leaf1 = new Leaf('leaf1');
const leaf2 = new Leaf('leaf2');
const composite = new Composite('composite');
composite.add(new Leaf('leaf3'));
composite.add(new Leaf('leaf4'));
root.add(leaf1);
root.add(leaf2);
root.add(composite);

// 调用对象树中的方法
root.operation();