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 ?
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.
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.
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With