/ Published in: JavaScript
The Command pattern aims to encapsulate method invocation, requests or operations
into a single object and gives you the ability to both parameterize and pass method calls
around that can be executed at your discretion. In addition, it enables you to decouple
objects invoking the action from the objects which implement them, giving you a
greater degree of overall flexibility in swapping out concrete 'classes'.
into a single object and gives you the ability to both parameterize and pass method calls
around that can be executed at your discretion. In addition, it enables you to decouple
objects invoking the action from the objects which implement them, giving you a
greater degree of overall flexibility in swapping out concrete 'classes'.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
(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)); }; /*** Usage ***/ CarManager.execute("arrangeViewing", "Ferrari", "14523"); CarManager.execute("requestInfo", "Ford Mondeo", "54323"); CarManager.execute("requestInfo", "Ford Escort", "34232"); CarManager.execute("buyVehicle", "Ford Escort", "34232");