Command Design Pattern In C# .NET

Command Design Pattern is a type of Behavioral Design Pattern.

Behavioral Design Pattern

It's about object communication, their responsibilities, and how they communicate to each other.

There might be a situation where we want to encapsulate the required information in an Object to perform some task and the task can be performed many times or whenever it's required. The command design pattern is the solution. It also gives you an easy way to implement Undo() that can just undo multiple commands.

  • Implementation - Typically, Implementation of Command Pattern is divided into 4 parts.
  • Command - That executes an action.
  • Receiver - Objects that receive the action from the command.

Invoker: Invoke the Commands to execute their actions. The Invoker may be a queue that holds commands for future execution, or holds such commands which can be used by different applications. The machine can be used to execute commands multiple times or can be used to undo the command.

Client

Client is the main program that asks for a command to be executed.

Consider the case of a banking application which is capable of making transactions i.e. Transfer, Deposit, Withdraw etc.

Let's identify each part of the command design pattern we discussed above.

Account of a customer ? Think, what it should be ?

Command ? Read command's definition again.......It says that it executes an action, but what action Account will it execute? Actions such as increment in account balance or decrements in account balance can be executed on Account by the Commands Deposit/Withdraw . So, if it receives actions, it means account is a Receiver.

So, Receiver is Account, and Command Deposit will add money from Account Balance and Withdraw command will subtract money from Account Balance.

  1. /// <summary>  
  2. /// Reciever of Command  
  3. /// </summary>  
  4. public class Account {  
  5.     public string CustomerName {  
  6.         get;  
  7.         set;  
  8.     }  
  9.     public double AccountBalance {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public Account(string customerName, double accountBalance) {  
  14.         CustomerName = customerName;  
  15.         AccountBalance = accountBalance;  
  16.     }  
  17. }  
  18. /// <summary>  
  19. /// Defines the action of Command those can be executed - will be called by Invoker  
  20. /// IsCommandCompleted signals the command is completed and can be removed from Invoker  
  21. /// </summary>  
  22. public interface ITransaction {  
  23.     void ExecuteCommand();  
  24.     bool IsCommandCompleted {  
  25.         get;  
  26.         set;  
  27.     }  
  28. }  
  29. /// <summary>  
  30. /// Deposit Command  
  31. /// </summary>  
  32. public class Deposit: ITransaction {  
  33.     private readonly Account _account;  
  34.     private readonly double _amount;  
  35.     public bool IsCommandCompleted {  
  36.         get;  
  37.         set;  
  38.     }  
  39.     public Deposit(Account account, double amount) {  
  40.         _account = account;  
  41.         _amount = amount;  
  42.         IsCommandCompleted = false;  
  43.     }  
  44.     public void ExecuteCommand() {  
  45.         _account.AccountBalance += _amount;  
  46.         IsCommandCompleted = true;  
  47.     }  
  48. }  
  49. /// <summary>  
  50. /// Withdraw Command  
  51. /// </summary>  
  52. public class Withdraw: ITransaction {  
  53.     private readonly Account _account;  
  54.     private readonly double _amount;  
  55.     public bool IsCommandCompleted {  
  56.         get;  
  57.         set;  
  58.     }  
  59.     public Withdraw(Account account, double amount) {  
  60.         _account = account;  
  61.         _amount = amount;  
  62.         IsCommandCompleted = false;  
  63.     }  
  64.     public void ExecuteCommand() {  
  65.         if (_account.AccountBalance >= _amount) {  
  66.             _account.AccountBalance -= _amount;  
  67.             IsCommandCompleted = true;  
  68.         }  
  69.     }  
  70. }  
  71. /// <summary>  
  72. /// Transfer Command  
  73. /// </summary>  
  74. public class Transfer: ITransaction {  
  75.         private readonly Account _fromAccount;  
  76.         private readonly Account _toAccount;  
  77.         private readonly double _amount;  
  78.         public bool IsCommandCompleted {  
  79.             get;  
  80.             set;  
  81.         }  
  82.         public Transfer(Account fromAccount, Account toAccount, double amount) {  
  83.             _fromAccount = fromAccount;  
  84.             _toAccount = toAccount;  
  85.             IsCommandCompleted = false;  
  86.         }  
  87.         public void ExecuteCommand() {  
  88.             _fromAccount.AccountBalance -= _amount;  
  89.             _toAccount.AccountBalance += _amount;  
  90.             IsCommandCompleted = true;  
  91.         }  

Lets write Invoker,

  1. public class TransactionManager {  
  2.     private readonly IList < ITransaction > _transactions = new List < ITransaction > ();  
  3.     public bool HasInCompleteTransactions {  
  4.         get {  
  5.             return _transactions.Any(x => !x.IsCommandCompleted);  
  6.         }  
  7.     }  
  8.     public IList < ITransaction > GetPendingTransactions() {  
  9.         return _transactions ? .Where(x => !x.IsCommandCompleted) ? .ToList();  
  10.     }  
  11.     public void AddTransaction(ITransaction transaction) {  
  12.         _transactions.Add(transaction);  
  13.     }  
  14.     public void ProcessPendingTransactions() {  
  15.         foreach(var transaction in _transactions.Where(x => !x.IsCommandCompleted)) {  
  16.             transaction.ExecuteCommand();  
  17.         }  
  18.     }  
  19. }  
  20. }  

The Client is responsible to create commands and pass them to the Invoker. The Commands will be held in the _transactions list, until the Client calls ProcessInCompleteTransactions. Then, the Invoker will try to execute each incomplete Command.

Invoker should not be aware of anything about what the Command can do, or what inputs it needs. All it needs to know is that the Command should be executed.

We will here simulate the client using our Console application to demonstrate.

  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         //Add 100 to the account - there should not be any pending job  
  4.         TransactionManager manager = new CommandPattern.TransactionManager();  
  5.         Account accountAshish = new CommandPattern.Account("Ashish", 0);  
  6.         ITransaction depositTransaction = new Deposit(accountAshish, 100);  
  7.         manager.AddTransaction(depositTransaction);  
  8.         manager.ProcessPendingTransactions();  
  9.         //try to withdraw 200 - transction will be pending since the balance is account is low  
  10.         ITransaction withdrawTransaction = new Withdraw(accountAshish, 200);  
  11.         manager.AddTransaction(withdrawTransaction);  
  12.         manager.ProcessPendingTransactions();  
  13.         var pendingTransaction = manager.HasInCompleteTransactions;  
  14.         Console.WriteLine(pendingTransaction);  
  15.         Console.ReadKey();  
  16.         //add 200- still withdraw trasaction would be pending since we are adding money after withdraw failed attempt,  
  17.         //we would need to execute failed transacction again  
  18.         ITransaction anotherDepositTransaction = new Deposit(accountAshish, 200);  
  19.         manager.AddTransaction(anotherDepositTransaction);  
  20.         manager.ProcessPendingTransactions();  
  21.         Console.WriteLine(manager.HasInCompleteTransactions);  
  22.         Console.ReadKey();  
  23.         if (manager.HasInCompleteTransactions) {  
  24.             //reattempt failed transactions  
  25.             ReattemptPendingTransactions(manager);  
  26.         }  
  27.         Console.WriteLine(manager.HasInCompleteTransactions);  
  28.         Console.ReadKey();  
  29.         //Try Transfer  
  30.         Account accountAvinash = new Account("Avinash", 10);  
  31.         ITransaction transferTransaction = new Transfer(accountAshish, accountAvinash, 10);  
  32.         manager.AddTransaction(transferTransaction);  
  33.         manager.ProcessPendingTransactions();  
  34.         Console.WriteLine("Ashish account balance:" + accountAshish.AccountBalance);  
  35.         Console.WriteLine("Anjali account balance:" + accountAvinash.AccountBalance);  
  36.         Console.ReadKey();  
  37.     }  
  38.     private static void ReattemptPendingTransactions(TransactionManager manager) {  
  39.         var pendingTransactions = manager.GetPendingTransactions();  
  40.         foreach(var item in pendingTransactions) {  
  41.             item.ExecuteCommand();  
  42.         }  
  43.     }  
  44. }  

Enhancement Undo

Suppose you want to undo the command. Modify your code, add Undo in your command.

You should facilitate your program with the undo all command and undo a particular command. In case of a particular command undo, you would need some kind of identifier which can uniquely identify the command (i.e. Id) and perform undo on it. We should be able to Undo successful commands also, we can have some status of command which tells us if command is executed successfully or not, unprocessed, Undo Successful, Undo Failed etc.

Transaction would look like,

  1. public interface ITransaction {  
  2.     int Id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     void ExecuteCommand();  
  7.     bool IsCommandCompleted {  
  8.         get;  
  9.         set;  
  10.     }  
  11.     void Undo();  
  12. }  

Implement modified interface in all the Commands Deposit, Withdraw and Transfer

Create an enum to set Command state

  1. /// <summary>  
  2. /// Command sate enum  
  3. /// </summary>  
  4. public enum CommandState {  
  5.     UnProcessed,  
  6.     ExecutionFailed,  
  7.     ExecutionSuccessed,  
  8.     UndoDone,  
  9.     UndoFailed  
  10. }  
  11. public interface ITransaction {  
  12.     int Id {  
  13.         get;  
  14.         set;  
  15.     }  
  16.     void ExecuteCommand();  
  17.     bool IsCommandCompleted {  
  18.         get;  
  19.         set;  
  20.     }  
  21.     CommandState Status {  
  22.         get;  
  23.         set;  
  24.     }  
  25.     void Undo();  
  26. } === === === === === == Other Updated Classes === === === === === === === === === === === == private static void ReattemptPendingTransactions(TransactionManager manager) {  
  27.     var pendingTransactions = manager.GetPendingTransactions();  
  28.     foreach(var item in pendingTransactions) {  
  29.         item.ExecuteCommand();  
  30.     }  
  31. }  
  32. }  
  33. /// <summary>  
  34. /// Reciever of Command  
  35. /// </summary>  
  36. public class Account {  
  37.     public string CustomerName {  
  38.         get;  
  39.         set;  
  40.     }  
  41.     public double AccountBalance {  
  42.         get;  
  43.         set;  
  44.     }  
  45.     public Account(string customerName, double accountBalance) {  
  46.         CustomerName = customerName;  
  47.         AccountBalance = accountBalance;  
  48.     }  
  49. }  
  50. /// <summary>  
  51. /// Defines the action of Command those can be executed - will be called by Invoker  
  52. /// IsCommandCompleted signals the command is completed and can be removed from Invoker  
  53. /// </summary>  
  54. public interface ITransaction {  
  55.     int Id {  
  56.         get;  
  57.         set;  
  58.     }  
  59.     void ExecuteCommand();  
  60.     bool IsCommandCompleted {  
  61.         get;  
  62.         set;  
  63.     }  
  64.     CommandState Status {  
  65.         get;  
  66.         set;  
  67.     }  
  68.     void Undo();  
  69. }  
  70. /// <summary>  
  71. /// Command sate enum  
  72. /// </summary>  
  73. public enum CommandState {  
  74.     UnProcessed,  
  75.     ExecutionFailed,  
  76.     ExecutionSuccessed,  
  77.     UndoDone,  
  78.     UndoFailed  
  79. }  
  80. /// <summary>  
  81. /// Deposit Command  
  82. /// </summary>  
  83. public class Deposit: ITransaction {  
  84.     private readonly Account _account;  
  85.     private readonly double _amount;  
  86.     public bool IsCommandCompleted {  
  87.         get;  
  88.         set;  
  89.     }  
  90.     public int Id {  
  91.         get;  
  92.         set;  
  93.     }  
  94.     public CommandState Status {  
  95.         get {  
  96.             throw new NotImplementedException();  
  97.         }  
  98.         set {  
  99.             throw new NotImplementedException();  
  100.         }  
  101.     }  
  102.     public Deposit(int Id, Account account, double amount) {  
  103.         this.Id = Id;  
  104.         _account = account;  
  105.         _amount = amount;  
  106.         IsCommandCompleted = false;  
  107.         Status = CommandState.UnProcessed;  
  108.     }  
  109.     public void ExecuteCommand() {  
  110.         _account.AccountBalance += _amount;  
  111.         IsCommandCompleted = true;  
  112.         Status = CommandState.ExecutionSuccessed;  
  113.     }  
  114.     public void Undo() {  
  115.         if (_account.AccountBalance >= _amount) {  
  116.             _account.AccountBalance -= _amount;  
  117.             Status = CommandState.UndoDone;  
  118.         } else {  
  119.             Status = CommandState.UndoFailed;  
  120.         }  
  121.     }  
  122. }  
  123. /// <summary>  
  124. /// Withdraw Command  
  125. /// </summary>  
  126. public class Withdraw: ITransaction {  
  127.     private readonly Account _account;  
  128.     private readonly double _amount;  
  129.     public bool IsCommandCompleted {  
  130.         get;  
  131.         set;  
  132.     }  
  133.     public int Id {  
  134.         get;  
  135.         set;  
  136.     }  
  137.     public CommandState Status {  
  138.         get;  
  139.         set;  
  140.     }  
  141.     public Withdraw(int Id, Account account, double amount) {  
  142.         _account = account;  
  143.         _amount = amount;  
  144.         IsCommandCompleted = false;  
  145.         this.Id = Id;  
  146.         Status = CommandState.UnProcessed;  
  147.     }  
  148.     public void ExecuteCommand() {  
  149.         if (_account.AccountBalance >= _amount) {  
  150.             _account.AccountBalance -= _amount;  
  151.             IsCommandCompleted = true;  
  152.             Status = CommandState.ExecutionSuccessed;  
  153.         } else {  
  154.             Status = CommandState.ExecutionFailed;  
  155.         }  
  156.     }  
  157.     public void Undo() {  
  158.         _account.AccountBalance += _amount;  
  159.         Status = CommandState.UndoDone;  
  160.     }  
  161. }  
  162. /// <summary>  
  163. /// Transfer Command  
  164. /// </summary>  
  165. public class Transfer: ITransaction {  
  166.     private readonly Account _fromAccount;  
  167.     private readonly Account _toAccount;  
  168.     private readonly double _amount;  
  169.     public bool IsCommandCompleted {  
  170.         get;  
  171.         set;  
  172.     }  
  173.     public int Id {  
  174.         get;  
  175.         set;  
  176.     }  
  177.     public CommandState Status {  
  178.         get;  
  179.         set;  
  180.     }  
  181.     public Transfer(int Id, Account fromAccount, Account toAccount, double amount) {  
  182.         _fromAccount = fromAccount;  
  183.         _toAccount = toAccount;  
  184.         IsCommandCompleted = false;  
  185.         _amount = amount;  
  186.         this.Id = Id;  
  187.         Status = CommandState.UnProcessed;  
  188.     }  
  189.     public void ExecuteCommand() {  
  190.         if (_fromAccount.AccountBalance >= +_amount) {  
  191.             _fromAccount.AccountBalance -= _amount;  
  192.             _toAccount.AccountBalance += _amount;  
  193.             IsCommandCompleted = true;  
  194.             Status = CommandState.ExecutionSuccessed;  
  195.         } else {  
  196.             Status = CommandState.ExecutionFailed;  
  197.         }  
  198.     }  
  199.     public void Undo() {  
  200.         if (_toAccount.AccountBalance >= _amount) {  
  201.             _toAccount.AccountBalance -= _amount;  
  202.             _fromAccount.AccountBalance += _amount;  
  203.             Status = CommandState.UndoDone;  
  204.         } else {  
  205.             Status = CommandState.UndoFailed;  
  206.         }  
  207.     }  
  208. }  
  209. public class TransactionManager {  
  210.     private readonly IList < ITransaction > _transactions = new List < ITransaction > ();  
  211.     public bool HasInCompleteTransactions {  
  212.         get {  
  213.             return _transactions.Any(x => !x.IsCommandCompleted);  
  214.         }  
  215.     }  
  216.     public IList < ITransaction > GetPendingTransactions() {  
  217.         return _transactions ? .Where(x => !x.IsCommandCompleted) ? .ToList();  
  218.     }  
  219.     public void AddTransaction(ITransaction transaction) {  
  220.         _transactions.Add(transaction);  
  221.     }  
  222.     public void ProcessPendingTransactions() {  
  223.         foreach(var transaction in _transactions.Where(x => !x.IsCommandCompleted)) {  
  224.             transaction.ExecuteCommand();  
  225.         }  
  226.     }  

Note

I won't create a client for these extended functionalities, I want you to try this. If you find any difficulty, please reach out to me through the Contact Us Page.

Command Design Pattern is often used with message queue applications such as, logging. In case of sudden system shut down/ crash, our system would be able read the incomplete commands from the queue, and resume without any data loss. Another scenario is if you want to interact with some service and that service is not available, this pattern will help you in reattempting the operation once service is up again.

Since it adds the complexity to the system, it is recommended to use this pattern in the big system where reliability is important.

Next Recommended Reading Implement Repository Pattern In .NET