链模式
实现方法链式调用的设计模式
问题
什么是链模式?如何实现链式调用?
解答
链模式是一种设计模式,通过让方法返回对象本身(this),实现连续调用多个方法。
基本实现
class Calculator {
constructor(value = 0) {
this.value = value;
}
add(num) {
this.value += num;
return this; // 返回 this 实现链式调用
}
subtract(num) {
this.value -= num;
return this;
}
multiply(num) {
this.value *= num;
return this;
}
divide(num) {
this.value /= num;
return this;
}
getResult() {
return this.value;
}
}
// 使用
const result = new Calculator(10)
.add(5) // 15
.multiply(2) // 30
.subtract(10) // 20
.divide(4) // 5
.getResult();
console.log(result); // 5
jQuery 风格的链式调用
class Query {
constructor(selector) {
this.elements = document.querySelectorAll(selector);
}
css(property, value) {
this.elements.forEach(el => {
el.style[property] = value;
});
return this;
}
addClass(className) {
this.elements.forEach(el => {
el.classList.add(className);
});
return this;
}
on(event, handler) {
this.elements.forEach(el => {
el.addEventListener(event, handler);
});
return this;
}
}
// 使用
const $ = selector => new Query(selector);
$('.box')
.css('color', 'red')
.css('fontSize', '16px')
.addClass('active')
.on('click', () => console.log('clicked'));
Promise 链式调用
// Promise 的 then 返回新的 Promise,实现链式调用
fetch('/api/user')
.then(res => res.json())
.then(user => fetch(`/api/posts/${user.id}`))
.then(res => res.json())
.then(posts => console.log(posts))
.catch(err => console.error(err));
构建器模式中的链式调用
class RequestBuilder {
constructor() {
this.config = {
method: 'GET',
headers: {},
body: null
};
}
setMethod(method) {
this.config.method = method;
return this;
}
setHeader(key, value) {
this.config.headers[key] = value;
return this;
}
setBody(body) {
this.config.body = JSON.stringify(body);
return this;
}
build() {
return this.config;
}
}
// 使用
const config = new RequestBuilder()
.setMethod('POST')
.setHeader('Content-Type', 'application/json')
.setHeader('Authorization', 'Bearer token')
.setBody({ name: 'test' })
.build();
console.log(config);
// { method: 'POST', headers: {...}, body: '{"name":"test"}' }
关键点
- 每个方法返回
this,使调用可以继续 - 提高代码可读性,减少临时变量
- jQuery、Promise、Lodash 都使用了链模式
- 构建器模式常与链模式结合使用
- 注意区分返回
this(同一对象)和返回新对象(如 Promise)的区别
目录