As usual, let us look at the definition of the Command
Pattern.
(1) Concept
The Command pattern encapsulates requests, invocations, or
operations into an object. In detail, the Command pattern allows the system to parameterize
the clients using different claims, queuing up the requests, recording request
records, etc. The Command pattern can separate the responsibilities of issuing commands
from those of executing commands, delegating them to the different objects.
(2) Example
In this section, I will explain the application of Command pattern
by dissecting the design idea of constructing a JavaScript based calculator application.
What first comes to my mind is to define the following
Calculator object which includes four methods relating to the four arithmetic operations
respectively.
Listing 22
var Calculator={
// addition
add: function(x,y) {
return x+y;
},
// subtraction
substract: function(x, y) {
return x-y;
},
// multiplication
multiply: function(x, y) {
return x*y;
},
// division
divide: function(x, y) {
return x/y;
},
};
To be honest, based on the above Calculator object, we can
carry out the four basic arithmetic operations by directly invoking the
methods, such as "Calculator.add," and "Calculator.substract,"
etc. In some circumstances, however, we do not expect to invoke the inner methods
inside the Calculator object directly. The reason for this is apparent: this
will increase the dependencies among objects. In another word, if the internal logics
of the Calculator object change, then all the code scripts that carry out the
calculations associated with the Calculator have to be modified in the
meantime. This, as you may imagine, will violate the principle advocated by
OOP-- to loosely couple the objects as much as possible.
According to the design pattern related theories put forward
by GoF, we can leverage the Command pattern to improve the above design. Here, the
basic idea of the Command pattern is: take any type of calculations as a request
to the Calculator object, the contents of a request including the type of
operation and the related operands. Hence, using the code below you can get the
result of the formula of "1+2."
Listing 23
Calculator.calc({
type: "add", // addition
op1:1, //the first operand is 1
op2:2 // the second operand is 2
});
According to the format above, we can conclude the definition
for the "Calculator.calc" method as follows:
Listing 24
Calculator.calc=function(command) {
return Calculator[command.type](command.opl,command.op2);
};
Consequently, we can use the following four "Calculator.calc"
methods to carry out each kind of above-mentioned operations.
Listing 25
Calculator.calc({type: "add",opl:1,op2:1});
Calculator.calc({type: "Substract",opl:6,op2:2});
Calculator.calc({type: "multiply",opl:5,op2:2));
Calculator.calc({type: "divide",opl:8,op2:4));