萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

深入理解 JavaScript 設計模式:命令模式詳解與車輛購買系統實戰

命令模式核心定義

將「請求」封裝為物件,從而用不同請求參數化客戶端;支援請求排隊、日誌記錄、可撤銷操作。核心角色:

  • Command:聲明執行介面 execute()。
  • ConcreteCommand:綁定接收者與動作,實現 execute() 呼叫接收者方法。
  • Invoker:持有命令物件,觸發 execute()。
  • Receiver:執行實際業務邏輯的物件。

重構前:直接呼叫接收者

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");

重構後:命令模式解耦

1. 定義執行入口 execute(command)

CarManager.execute = function(command) {
  return CarManager[command.request](command.model, command.carID);
};

2. 統一命令格式調用

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();
  }
};

命令模式適用場景

  • GUI 按鈕/選單:每個動作封裝為命令,統一分發。
  • 巨集錄製/回放:記錄命令序列,支援重播。
  • 資料庫交易:命令封裝 SQL,支援 Commit/Rollback。
  • 非同步任務隊列:命令入隊,Worker 執行緒消費。

敏捷原則提醒

「不要為投機性功能添加複雜度」。若系統不需要撤銷、日誌、排隊,直接呼叫方法更簡潔。真正需要時再重構為命令模式不遲。

命令模式將「請求」物件化,賦予請求生命週期(建立、排隊、執行、撤銷、記錄)。JavaScript 的物件字面量與一等函式,讓輕量級命令實作變得極簡:{execute: fn, undo: fn} 即可上路。視系統複雜度決定是否引入完整結構。

copyright © 萬盛學電腦網 all rights reserved