How The Pattern Works
A simple example of a common problem the Command Design Pattern is well suited to solve is the evaluation and execution of an incoming HttpServletRequest action parameter command from a submit on a JSP page.
Most servlets in the M-V-C Model 2 form (i.e. Struts framework type) redirect both their doGet() and doPost() methods to a perform() or performTask() method after stripping out the relevant data from the HttpServletRequest. Thus, we can pass an already constructed object graph the system will then manipulate. To keep things simple, we will just pass the performTask() method of our servlet a String action parameter such as "create", "replace", "update", etc.
In pre-design pattern days, these action parameters would be handled via large blocks of conditional logic in the servlet. Then it was seen that refactoring this logic out into separate private or protected methods produced simpler to read code. However, as web based applications demonstrated the complex logic needed in servlet code, it was seen that groups of these methods solving related business issues really needed to become separate servlets or just regular classes in their own right. This was the separation into the M-V-C design pattern of solution where a controller servlet delegated its work to other specialized servlets or classes.
But the conditional logic in these receiving servlets was still too complex to deal with in the doPost() or performTask() method. The Command Design Pattern provided a way to meld object inheritance among an abstract factory class with its discrete and highly encapsulated and loosely coupled descendant concrete classes to simplify the controlling servlet's api and work load.
This document will look at these 3 ways of accomplishing the same goal:
- Common Parameter Request Handling - Implementing code within conditional statement activated by the action parameter.
- Replacing Conditional Logic With Objects - Calling out to service objects to execute code specific to the conditional statement activated by the action parameter.
- Implementing The Command Design Pattern - Direct instantiation and polymorphic implementation of an object without conditional statements.