Sunday, June 21, 2009

Command Design Pattern

When one object has to issue a request to another object without know anything about the object that is receiving the request or the operation that is being requested.

Following is a class diagram of various entities:



invoker - the object that needs to make the request without knowing receiever
Command - the interface that specifies the APIs that Command implementations must realize/implement.
CommandImpl - A implementation of Command that contains logic to realize command. Usually delegates to a receiver.
Receiver - Object that contains the actual business logic to realize the request. This usually has no web or struts context.

For example the struts framework must invoke application logic without knowing which application object is receiving the request or what operation is being performed by the application object. To achieve this, struts exposes Action interface. Application action classes must implement the struts action interface. The responsibility of the struts action implementation is to realize the business functionality. To do so, the action implementation usually invoke a application object (a pure business object that has no dependency on struts or has not web context). This application object, in the context of Command Design Pattern, is referred to as a receiver.

The struts ActionServlet handles the in-bound request and invokes RequestProcessor.process method. This method as part of the many things it does, has a reference to an Action implementation (specified in struts-config.xml) and invokes Action.execute(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse) without knowing which action implementation it is invoking or the operation it is performing..

The Action interface is a good example of Command component in Command design pattern.



Struts classes: Source

No comments: