JS Command Pattern
Example of the Command Design Pattern in JavaScript. Car Manager object is decoupled from the program by using an execute method, which accepts any process requests from the CarManager object where the contents of the request include model and carID.
by secretgspot
JavaScript
// Command Pattern (explained in detail here: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#commandpatternjavascript)
$(function(jQuery){
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 + ' )';
}
};
// This added execute method decouples the CarManager's internal methods from the rest of the application
CarManager.execute = function(command) {
return CarManager[command.request](command.model, command.carID);
};
console.log(CarManager.execute({request: "arrangeViewing", model: 'Ferrari', carID: '146326'}));
console.log(CarManager.execute({request: "requestInfo", model: 'Ford Mondeo', carID: '544356'}));
console.log(CarManager.execute({request: "requestInfo", model: 'Ford Escort', carID: '63341'}));
console.log(CarManager.execute({request: "buyVehicle", model: 'Ford Escort', carID: '63341'}));
})(jQuery);