I need to execute several commands in a specific order but before I excute the main command, another command needs to be executed first and in some situations there are more commands that also need to be executed last.
To achieve this I build an extended chain of resposibility. It does not only have a post-command but also a pre-command. The main command in the middle is the one that a user sees in a menu.
internal abstract class Command
{
public Command Pre { get; set; }
public Command Post { get; set; }
public int Execute()
{
var executedCommandCount = 0;
if (Pre != null)
{
var preResult = Pre.Execute();
if (preResult == 0) { return executedCommandCount; }
executedCommandCount += preResult;
}
if (!ExecuteCore())
{
return executedCommandCount;
}
executedCommandCount++;
if (Post != null)
{
var postResult = Post.Execute();
if (postResult == 0) { return executedCommandCount; }
executedCommandCount += postResult;
}
return executedCommandCount;
}
protected abstract bool ExecuteCore();
}
Test commands:
class FirstCommand : Command
{
protected override bool ExecuteCore()
{
return true;
}
}
class MainCommand : Command
{
protected override bool ExecuteCore()
{
return true;
}
}
class LastCommand : Command
{
protected override bool ExecuteCore()
{
return true;
}
}
Example:
var mainCommand = new MainCommand
{
Pre = new FirstCommand(),
Post = new LastCommand()
};
var executedCommandCount = mainCommand.Execute(); // 3