Wednesday, December 9, 2009

Not So Obvious Uses for the Command Pattern

For those not familiar with the Command Pattern, it is what all good design patterns should be - simple, elegant, and powerful.

At its most basic it looks like:

   1: public interface ICommand
   2: {
   3:     void Execute();
   4: }

You can also dress it up a bit to support undo:

   1: public interface ICommand
   2: {
   3:     void Execute();
   4:     void Undo();
   5: }

One of the other variations of the command pattern adds the CanExecute property:

   1: public interface ICommand
   2: {
   3:     void Execute();
   4:     void Undo();
   5:     bool CanExecute { get; }
   6: }

So let’s look at some “not so obvious” uses for this pattern.

Use the command pattern to execute transactions

In this scenario, you would add the commands to be transacted to a queue. When you were ready to perform the transaction, you would iterate the queue calling the Execute method on each command object.

Use the command pattern for exception handling or logging

In this scenario, create a RaiseErrorCommand (or something similar)class. This can be used for failed validation or logging purposes and called from anywhere in the code, including other commands.

Use the command pattern in the UI

Bind toolbar buttons and menu item enabled or visible property directly to command objects that implement CanExecute. When CanExecute changes (evaluates to true or false), the UI will reflect the change.

Use the command pattern for unit or integration testing

This one is very simple and very powerful. Create command classes that implement Undo functionality. Use the command for performing actions to be tested, test the result, and then use the Undo method to restore the system under test and remove the footprint.

Give these ideas a try and have fun with it. Please feel free to share creative ways you may have for using the command pattern.

No comments:

Post a Comment