將「請求」封裝為物件,從而用不同請求參數化客戶端;支援請求排隊、日誌記錄、可撤銷操作。核心角色:
execute()。execute() 呼叫接收者方法。execute()。var CarManager = {
requestInfo: function(model, id) { return 'Info: ' + model + ' ' + id; },
buyVehicle: function(model, id) { return 'Purchased: ' + model + ' ' + id; },
arrangeViewing: function(model, id) { return 'Booked: ' + model + ' ' + id; }
};
// 直接耦合調用
CarManager.buyVehicle("Ford Escort", "453543");
CarManager.execute = function(command) {
return CarManager[command.request](command.model, command.carID);
};
CarManager.execute({ request: "arrangeViewing", model: "Ferrari", carID: "145523" });
CarManager.execute({ request: "requestInfo", model: "Ford Mondeo", carID: "543434" });
CarManager.execute({ request: "buyVehicle", model: "Ford Escort", carID: "543434" });
// 抽象命令
var Command = function() {};
Command.prototype.execute = function() { throw new Error("Unimplemented"); };
Command.prototype.undo = function() { throw new Error("Unimplemented"); };
// 具體命令:購車
var BuyVehicleCommand = function(manager, model, id) {
this.manager = manager; this.model = model; this.id = id;
this.backup = null;
};
BuyVehicleCommand.prototype = new Command();
BuyVehicleCommand.prototype.execute = function() {
this.backup = this.manager.getState(); // 假設有狀態備份
return this.manager.buyVehicle(this.model, this.id);
};
BuyVehicleCommand.prototype.undo = function() {
this.manager.restoreState(this.backup);
};
// 執行器:命令隊列 + 歷史堆疊
var Invoker = function() {
this.history = []; this.queue = [];
};
Invoker.prototype = {
add: function(cmd) { this.queue.push(cmd); },
run: function() {
while (this.queue.length) {
var cmd = this.queue.shift();
cmd.execute();
this.history.push(cmd);
}
},
undo: function() {
var cmd = this.history.pop();
if (cmd) cmd.undo();
}
};
「不要為投機性功能添加複雜度」。若系統不需要撤銷、日誌、排隊,直接呼叫方法更簡潔。真正需要時再重構為命令模式不遲。
命令模式將「請求」物件化,賦予請求生命週期(建立、排隊、執行、撤銷、記錄)。JavaScript 的物件字面量與一等函式,讓輕量級命令實作變得極簡:{execute: fn, undo: fn} 即可上路。視系統複雜度決定是否引入完整結構。