介绍
链模式,用于链式调用,例如 Promise 的链式调用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class CarBuilder { constructor(param) { this.param = param } buildPart1() { this.part1 = 'part1' return this } buildPart2() { this.part2 = 'part2' return this } }
const car = new CarBuilder('param').buildPart1().buildPart2()
|
在 vue 中我们经常会看见类似下面的链式调用,使用了多个插件。
1
| app.use(router).use(Antd).use(pinia);
|
vue3 中 App 的接口描述如下:
1 2 3
| interface App { use(plugin: Plugin, ...options: any[]): this }
|
可以看到 use 方法返回了 this,实现了链式调用。 当然我们也可以返回其他的对象,在责任链模式中可以返回下一个处理者,实现链式调用。