【发布时间】:2017-07-14 18:29:39
【问题描述】:
我正在阅读命令模式,并且看到来自不同站点的示例,这些示例似乎使用桥接+命令模式来展示命令模式。
首先,来自维基百科: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" ));
})();
这个例子没有多余的东西,我只看到命令模式。但是,回到 Wikipedia,他们使用以下示例来展示命令模式:
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 使其
carManager对象在 IIFE 之外可用(它没有),它也没有.execute()方法。 -
对不起,我没有正确复制代码示例。已更正。
-
您能否澄清一下上述示例究竟让您感到困惑的是什么,以及您想知道什么?
-
我刚刚用第三个示例编辑了我的问题,以帮助澄清我在问什么。
标签: javascript design-patterns command bridge