建造者模式
定义
建造者模式(builder pattern):将一个复杂对象的构建过程拆分成多个步骤,并允许按步骤构建最终对象。
“就像去赛百味(Subway)点汉堡,不是直接给老板一句‘来个汉堡’,而是分步骤:选面包 -> 加选肉 -> 选蔬菜 -> 挤酱料,最后老板把你一步步选好的东西‘建造’成一个专属汉堡交给你。”
实现(链式调用)
js
// 最终要生成的产品:RequestConfig
class RequestConfig {
constructor(url, method, headers, params, body, timeout) {
this.url = url;
this.method = method;
this.headers = headers;
this.params = params;
this.body = body;
this.timeout = timeout;
}
}
// 建造者类:专门用来一步步“组装” RequestConfig
class RequestBuilder {
constructor() {
// 初始化默认值
this.config = {
url: '',
method: 'GET',
headers: {},
params: {},
body: null,
timeout: 5000
};
}
// 以下是一系列“组装步骤”,核心秘诀是:必须 return this
setUrl(url) {
this.config.url = url;
return this;
}
setMethod(method) {
this.config.method = method.toUpperCase();
return this;
}
addHeader(key, value) {
this.config.headers[key] = value;
return this;
}
setTimeout(ms) {
this.config.timeout = ms;
return this;
}
// 最终的“出厂”方法:将拼装好的数据产出为真实对象
build() {
return new RequestConfig(
this.config.url,
this.config.method,
this.config.headers,
this.config.params,
this.config.body,
this.config.timeout
);
}
}
// === 客户端调用演示 ===
// 不再使用恶心的 new RequestConfig('api/user', 'POST', {...}, null, null, 10000)
// 而是像拼乐高一样,逻辑极其清晰:
const myRequest = new RequestBuilder()
.setUrl('/api/user/update')
.setMethod('POST')
.addHeader('Authorization', 'Bearer token123')
.setTimeout(10000)
.build(); // 最后调用 build 产出对象
console.log(myRequest);
前端应用
1. SQL / 查询构建
js
const query = new QueryBuilder()
.select('*')
.from('user')
.where('id=1')
.build()
2. Webpack 配置生成
js
// Vue CLI 内部就是这样生成 Webpack 配置的
config.module
.rule('compile')
.test(/\.js$/)
.include
.add('src')
.end() // 类似退回上一级的建造者节点
.use('babel')
.loader('babel-loader')
.options({ presets: ['@babel/preset-env'] });