我正在閱讀命令模式,我看到來自不同站點的示例,它們似乎使用橋接+命令模式來展示命令模式。橋樑+命令模式
因此,首先,維基百科:https://en.wikipedia.org/wiki/Command_pattern,命令模式的定義:
該命令模式是在其中一個對象 用於封裝要執行的動作所需要的所有信息的行爲設計圖案或 稍後觸發事件。該信息包括方法 名稱,擁有方法的對象和方法 參數的值。
因此,根據該定義,命令模式看起來很簡單,閱讀這本書:https://addyosmani.com/resources/essentialjsdesignpatterns/book/#commandpatternjavascript,這個例子就是這樣。
(function(){
var carManager = {
// request information
requestInfo: function(model, id){
return "The information for " + model + " with ID " + id + " is foobar";
},
// purchase the car
buyVehicle: function(model, id){
return "You have successfully purchased Item " + id + ", a " + model;
},
// arrange a viewing
arrangeViewing: function(model, id){
return "You have successfully booked a viewing of " + model + " (" + id + ") ";
}
};
carManager.execute = function (name) {
return carManager[name] && carManager[name].apply(carManager, [].slice.call(arguments, 1));
};
console.log(carManager.execute("arrangeViewing", "Ferrari", "14523"));
console.log(carManager.execute("requestInfo", "Ford Mondeo", "54323"));
console.log(carManager.execute("requestInfo", "Ford Escort", "34232"));
console.log(carManager.execute("buyVehicle", "Ford Escort", "34232"));
})();
在這個例子中沒有額外的東西,我只看到命令模式。然而,回維基百科,他們用下面的例子來展示命令模式:
class Switch {
constructor() {
this._commands = [];
}
storeAndExecute(command) {
this._commands.push(command);
command.execute();
}
}
class Light {
turnOn() { console.log('turn on') }
turnOff() { console.log('turn off') }
}
class FlipDownCommand {
constructor(light) {
this._light = light;
}
execute() {
this._light.turnOff();
}
}
class FlipUpCommand {
constructor(light) {
this._light = light;
}
execute() {
this._light.turnOn();
}
}
var light = new Light();
var switchUp = new FlipUpCommand(light);
var switchDown = new FlipDownCommand(light);
var s = new Switch();
s.storeAndExecute(switchUp);
s.storeAndExecute(switchDown);
當我看到上面這個例子中,我立刻看到橋模式,然後立即看到命令模式,因爲它們被儲存,然後調用這些命令。
我的問題是這樣的;我正確地認爲維基百科的例子是使用橋樑+命令模式來展示命令模式嗎?
編輯:
如果我把第二個例子,和刪除命令的部分,這是不是橋模式?
class Light {
turnOn() { console.log('turn on') }
turnOff() { console.log('turn off') }
}
class FlipDownCommand {
constructor(light) {
this._light = light;
}
execute() {
this._light.turnOff();
}
}
class FlipUpCommand {
constructor(light) {
this._light = light;
}
execute() {
this._light.turnOn();
}
}
var light = new Light();
var switchUp = new FlipUpCommand(light);
var switchDown = new FlipDownCommand(light);
switchUp.execute();
switchDown.execute();
不確定橋/命令的東西,但作爲命令示例顯示的JS代碼不起作用。即使IIFE在IIFE外部提供了「carManager」對象(它沒有),它也沒有'.execute()'方法。 – nnnnnn
對不起,我沒有正確複製代碼示例。這已得到糾正。 –
您能否澄清一下您對上述示例的疑惑,以及您想知道的內容? – gyre