Java Code Geeks

Friday, November 21, 2008

Command Design Pattern in J2EE

Command is one of the oldest design pattern which exists from the days of SmallTalk. It is popular for its simplicity and yet the power. The heart of this pattern is its command interface which can have simple methods like init (), execute(). The concrete command objects will implement this interface. This design pattern can take a request and pass that to the proper object for being processed without any knowledge from client. The client code does not need to know actually which concrete object is going to process this request.
In J2EE world, to adhere to MVC model, there are several design patterns available to wrap the business logic or model. For example, EJB uses Facade Design pattern and hides the model complexities from controller. Similarly Struts framework uses something called "actions". If you do not want to use EJB or Struts type of framework, yet want to adhere to MVC model, its best to use Command Design pattern. Here is a small description how -

Develop some command beans which needs to have series of Set methods to set the parameters, a series of get methods to get the results after the processing, one init method to initialize (like open JDBC connection etc) the environment before processing start and finally one execute method to really perform the processing.

Develop one command interface which will have init and execute method so that the Controller Servlet can use this interface to send the processing request without really knowing which concrete command object will process it.
Lot of time we can use Class.forName to initialize the concrete command object. For example, in the controller servlet we can have some code like this -

DBCommandBean command = (DBCommandBean)Class.forName("com.mycom."+requestType+"CommandBean).newInstance();
command.set(hashtable) -- hashtable contains some parameter and value which will be used for processing.
command.execute() -- this will perform the real processing
command.get() -- this will give back one hashtable with key and value pairs which need to be accessed to see the result of the processing.

No comments: