组合模式(Composite Pattern)
|
1 2 3 |
定义:又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。 目的:将对象组合成树形结构以表示"部分-整体"的层次结构。 场景:您想表示对象的部分-整体层次结构(树形结构),如:文件系统。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
class Command { execute() { throw new Error('子类必须实现 execute() 方法') } } class SimpleCommand extends Command { constructor(action) { super() if (typeof action !== 'function') { throw new TypeError('action 必须是函数') } this.action = action } execute() { return this.action() } } class CompositeCommand extends Command { #children = [] add(command) { if (!(command instanceof Command)) { throw new TypeError('只能添加 Command 类型的对象') } if (command === this) { throw new Error('不能将组合对象添加到自身') } this.#children.push(command) return this } remove(command) { const index = this.#children.indexOf(command) if (index !== -1) { this.#children.splice(index, 1) } return this } execute() { for (const command of this.#children) { command.execute() } } } |
// 创建叶子指令:
|
1 2 3 4 5 6 7 8 9 10 11 |
const eat = new SimpleCommand(() => { console.log('eat') }) const sleep = new SimpleCommand(() => { console.log('sleep') }) const code = new SimpleCommand(() => { console.log('Get out there and write code!') }) |
// 组合使用:
|
1 2 3 4 5 6 7 8 9 |
const morning = new CompositeCommand() .add(eat) .add(code) const daily = new CompositeCommand() .add(morning) .add(sleep) daily.execute() |

