Search code examples
c#design-patternscommand-pattern

Command Pattern: Executing multiple commands in sequence


I want to issue a series of Command executions, but only when the prior command succeeded. Right now i am raising an event within the command object indicating whether the command succeeded or failed. I am using this to control execution, but it feels inelegant.

Example:

command1.CommandSucceeded += delegate { command2.Execute(); };
command1.Execute();

This works, but it feels clumsy and unintuitive. I could pass a boolean back on Execute() indicating success or failure, but that is along the same path. I could throw exceptions on failure, which would might result in cleaner code, but might be overkill.

Any suggestions?


Solution

  • I got around this by setting up a command "chain". I created a Command object that holds other commands, then fire each of them in turn when Do is called. In your case, you could have the command call the delegate and only fire off the next command in the sequence if it was successful.

    One way to do it, I suppose.