Search code examples
c#design-patternscommand-pattern

Command Pattern : How to pass parameters to a command?


My question is related to the command pattern, where we have the following abstraction (C# code) :

public interface ICommand
{
    void Execute();
}

Let's take a simple concrete command, which aims to delete an entity from our application. A Person instance, for example.

I'll have a DeletePersonCommand, which implements ICommand. This command needs the Person to delete as a parameter, in order to delete it when Execute method is called.

What is the best way to manage parametrized commands ? How to pass parameters to commands, before executing them ?


Solution

  • You'll need to associate the parameters with the command object, either by constructor or setter injection (or equivalent). Perhaps something like this:

    public class DeletePersonCommand: ICommand
    {
         private Person personToDelete;
         public DeletePersonCommand(Person personToDelete)
         {
             this.personToDelete = personToDelete;
         }
    
         public void Execute()
         {
            doSomethingWith(personToDelete);
         }
    }