I'm exploring the command pattern, and I'm trying to figure out the actual benefit of this pattern.
I have read the following article: http://ift.tt/1Kgj2u7
And after staring at it long enough, I still fail to see the benefit of the implementation. Let me clarify what I don't get.
We have the following command object:
(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 + " ) ";
}
};
})();
Executed by:
CarManager.execute = function ( name ) {
return CarManager[name] && CarManager[name].apply( CarManager, [].slice.call(arguments, 1) );
};
The article says that this is what we want to achieve:
CarManager.execute( "buyVehicle", "Ford Escort", "453543" );
The explanation is what I have problems with:
Taking a look at the above code, it would be trivial to invoke our CarManager methods by directly accessing the object. We would all be forgiven for thinking there is nothing wrong with this—technically, it’s completely valid JavaScript. There are however scenarios in which this may be disadvantageous.
For example, imagine if the core API behind the CarManager changed. This would require all objects directly accessing these methods within our application to also be modified. This could be viewed as a layer of coupling, which effectively goes against the OOP methodology of loosely coupling objects as much as possible. Instead, we could solve this problem by abstracting the API away further.
What I fail to see is how this solution is in any way beneficial over:
CarManager.buyVehicle("Ford Escort", "453543");
What do they mean "if the core API" changes? I assume that they are talking about the interface, ie. the methods of the command object and their implementations. But if either of them change, it doesn't seem to change anything in how the method is called (whether to use execute or not, both will not work if the method name changes).
Also, I don't see how the execute method decouples anything. Whether execute is called, or whether the method is executed directly, the calling object needs a reference to the command object anyway.
Also, in the article (see visual scheme), they mention a client, receiver, invoker and command object. In the example, I only see two objects (?).
Can someone enlighten me?
Aucun commentaire:
Enregistrer un commentaire