Tutorials Design Patterns Mastery

Command Pattern: Implementing Undo/Redo & Queueing

On this page

The Command Pattern

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.

1. Decoupling Sender and Receiver

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);
}

2. Implementation: The Command History

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.

4. Interview Mastery

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."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns Mastery
Course syllabus
1. Introduction to Design Patterns
2. Creational Patterns
3. Structural Patterns
4. Behavioral Patterns
5. Modern Enterprise & Cloud Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details