我正在阅读命令模式,我看到来自不同站点的示例,它们似乎使用桥接+命令模式来展示命令模式。桥梁+命令模式
因此,首先,维基百科: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