流暢接口 旨在構建接近自然語言的 API,方法鏈 是常用實現手段。Martin Fowler 指出:流暢接口不僅是鏈式調用,更關鍵在於領域語言 (DSL) 的表達力。
// 命令式 DOM 操作
var btn = document.createElement('button');
var txt = document.createTextNode('CLICK ME');
btn.appendChild(txt);
document.body.appendChild(btn);
// jQuery 流暢風格
$('
class QueryBuilder {
constructor(table) {
this._table = table;
this._where = [];
this._order = '';
this._limit = null;
}
where(field, op, value) {
this._where.push({field, op, value});
return this;
}
andWhere(field, op, value) { return this.where(field, op, value); }
orWhere(field, op, value) {
this._where.push({field, op, value, logic: 'OR'});
return this;
}
orderBy(field, dir = 'ASC') {
this._order = field + ' ' + dir;
return this;
}
limit(n) { this._limit = n; return this; }
toSQL() {
var sql = 'SELECT * FROM ' + this._table;
if (this._where.length) {
sql += ' WHERE ' + this._where.map(w =>
(w.logic || '') + ' ' + w.field + ' ' + w.op + ' ' + this._escape(w.value)
).join(' ');
}
if (this._order) sql += ' ORDER BY ' + this._order;
if (this._limit) sql += ' LIMIT ' + this._limit;
return sql;
}
_escape(v) { return typeof v === 'string' ? "'" + v.replace(/'/g, "''") + "'" : v; }
// 終結方法:執行並返回 Promise
exec(db) { return db.query(this.toSQL()); }
}
// 使用:幾乎像讀英語句子
var sql = new QueryBuilder('users')
.where('age', '>', 18)
.andWhere('status', '=', 'active')
.orWhere('role', '=', 'admin')
.orderBy('created_at', 'DESC')
.limit(10)
.toSQL();
console.log(sql);
// SELECT * FROM users WHERE age > 18 AND status = 'active' OR role = 'admin' ORDER BY created_at DESC LIMIT 10
where().andWhere().orderBy())。this 維持鏈式,終結方法 (exec(), toSQL()) 返回結果。end()、build()、exec() 明確結束鏈。$(sel).css().animate().on()_(arr).map().filter().value()moment().add(1,'day').format()axios.get().then().catch() (Promise 鏈)this (如 console.log 返回 undefined 即可)。this 類型標註 (this: this) 保持類型鏈推導。