The Command Pattern turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as method arguments, delay or queue a request's execution, and support undoable operations.
Normally, a button calls Database.Save(). If you use the Command pattern, the button calls Command.Execute(). The button has no idea what the command actually does, making it perfectly reusable.
public interface ICommand
{
void Execute();
void Undo(); // The secret to Undo/Redo!
}
public class SaveUserCommand : ICommand
{
private readonly User _user;
public void Execute() => _db.Save(_user);
public void Undo() => _db.Delete(_user.Id);
}
By storing executed commands in a Stack<ICommand>, you can implement a global Undo feature. When the user hits Ctrl+Z, you pop the last command and call its .Undo() method.
Q: "What is the difference between Strategy and Command?"
Architect Answer: "The **Strategy** pattern is used to change *How* an object does something (it’s an algorithm). The **Command** pattern is used to change *What* an object does (it’s a request). You use Strategy at the start of a task to pick a path; you use Command to store that task so you can run it later, log it, or undo it."