Re: Command action pattern
Friday, December 6, 2002 03:21 AM
The GoF "Design Patterns" book gives a good definition (Gamma et al). Here's my brief synopsis:
Command encapsulates a request as an object, letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Make each action into a subclass that encapsulates the specific operation to be performed. This way, when new actions are added to the application, you can simply add new subclasses. The subclasses have a abstract Command superclass with abstract method Execute which is overridden by the concrete subclasses.
This encapsulation allows the actions to be isolated and used for many purposes. The key is the isolation of the Execute method, which is attached to the class rather than repeated in application code each time the action is invoked.
It has been said that Commands are an object-oriented replacement for callbacks (such as in a procedural language like C).
You can find a good example of Commands in the Java Swing Action Interface. Check it out, and hopefully the example should clarify it further.