Design Patterns: Command

Hands-On

public interface ICommand
{
void Execute();
bool CanExecute(); void Undo();
}
public class CommandManager
{
private Stack<ICommand> commands = new Stack<ICommand>();
public void Invoke(ICommand command)
{
if (command.CanExecute())
{
commands.Push(command);
command.Execute();
}
}
public void Undo()
{
while(commands.Count > 0)
{
var command = commands.Pop();
command.Undo();
}
}
}
public class AddClientCommand : ICommand
{
private readonly IClientRepository _clientRepository;
private readonly Client _client;
public AddClientCommand(IClientRepository clientRepository, Client client) =>
(_clientRepository, _client) = (clientRepository, client);
public bool CanExecute()
{
if (_client == null)
return false;
return _clientRepository.GetClient(_client.Id) == null;
}
public void Execute()
{
if (_client == null)
return;
_clientRepository.Add(_client);
}
public void Undo()
{
if (_client == null)
return;
_clientRepository.Remove(_client.Id);
}
}
class Program
{
static void Main(string[] args)
{
IClientRepository clientRepository = default;
Client client = default;

var addClientCommand = new AddClientCommand(clientRepository, client);

var manager = new CommandManager();
manager.Invoke(addClientCommand);

// ... do something

manager.Undo();
}
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store