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:
You can also dress it up a bit to support undo:
One of the other variations of the command pattern adds the CanExecute property:
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.