The Command Pattern is well-know pattern in the OO community. Originally described in the Gang of Four book there have been multiple variants over time (e.g. http://www.javaworld.com/javaworld/javatips/jw-javatip68.html). The main characteristics of the Command pattern are:
- separates the Client of a function from the Receiver through Commands. This separation provides the flexibility to extend independently the client and the receiver;
- the Command is a first class entity that can be manipulated outside the client or receiver. This allows to create new commands from the existing ones through inheritance, group multiple commands in one and add transaction capabilities. The Command is a reification of the method invocation by the client on the receiver.
The original command pattern is powerful in itself, but working with it in multiple projects I found some limitations:
- the Command object knows (i.e. is coupled with) the Receiver in order to invoke the method. That means that the Client, which builds the Commands is also aware of the Receiver (even if not all the details). This is against the original intent of the pattern which is to decouple the client from the receiver;
- in most cases the Client is interested in the results of executing a Command. Only rarely a client has a “send-and-forget” behaviour. There are ways to pass back the results to the client for example by having a “shared” context between the client and the receiver. This solution creates a hidden dependency. A better option is for the client to register for command execution updates through the Command;
- often a Command invokes multiple Receivers in the same execution.
The article is about extensions to the Command Pattern to avoid these limitations.