Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 559
Romain Verdier Avatar asked Sep 19 '08 19:09

Romain Verdier


People also ask

How does the Command design pattern work?

The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parametrized with different requests. The "check" at a diner is an example of a Command pattern. The waiter or waitress takes an order or command from a customer and encapsulates that order by writing it on the check.

What does the Command pattern encapsulate?

Definition: The command pattern encapsulates a request as an object, thereby letting us parameterize other objects with different requests, queue or log requests, and support undoable operations.

What is the Command pattern good for?

The command pattern should be used when: You need a command to have a life span independent of the original request, or if you want to queue, specify and execute requests at different times. You need undo/redo operations. The command's execution can be stored for reversing its effects.


1 Answers

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);      } } 
like image 72
Blair Conrad Avatar answered Sep 28 '22 03:09

Blair Conrad