天天看點

js設計模式【詳解】—— 指令模式

指令模式的定義

指令模式(Command):将請求以指令的形式包裹在對象中,并傳給調用對象。調用對象尋找可以處理該指令的合适的對象,并把該指令傳給相應的對象,該對象執行指令。

類型:行為型模式

用途:把調用對象(使用者界面、API和代理等)與實作操作的對象隔離開。

使用場景:對行為進行"記錄、撤銷/重做、事務"等處理,需要行為請求者與行為實作者解耦的時候(凡是兩個對象間互動方式需要有更高的子產品化程度時都可以用到這種模式)

優點:

1.降低對象之間的耦合度。

2.新的指令可以很容易地加入到系統中。

3.可以比較容易地設計一個組合指令。

4.調用同一方法實作不同的功能

缺點:

使用指令模式可能會導緻某些系統有過多的具體指令類。

示範範例——指令模式

【構造函數】指令 —— 執行指令(execute )時 ,便會執行各自指令接收者的action方法

var CreateCommand = function( receiver ){
     this.receiver = receiver;
}

CreateCommand.prototype.execute = function() {
     this.receiver.action();
}      

【構造函數】接收者——電視——打開電視    

var TVOn = function() {}

TVOn.prototype.action = function() {
     alert("TVOn");
}      

【構造函數】接收者——電視——關閉電視          

var TVOff = function() {}

TVOff.prototype.action = function() {
     alert("TVOff");
}      

【構造函數】調用者——遙控器          

var Invoker = function( tvOnCommand, tvOffCommand ) {
      this.tvOnCommand = tvOnCommand;
      this.tvOffCommand = tvOffCommand;
}

Invoker.prototype.tvOn = function() {
      this.tvOnCommand.execute();
}

Invoker.prototype.tvOff = function() {
      this.tvOffCommand.execute();
}      
var tvOnCommand = new CreateCommand( new TVOn() );
var tvOffCommand = new CreateCommand( new TVOff() );
var invoker = new Invoker( tvOnCommand, tvOffCommand );
invoker.tvOn();
invoker.tvOff();      

繼續閱讀