Design Patterns

Last Updated: 9/28/2024

Command

  • Turns/Encapsulates a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method argument, delay or queue a request’s execution, and support undoable operations.
  • Used in lot of frameworks

Classical Structure

Command Classical Structure

Scenario

  • Build a GUI framework to build app with it. In the framework define classes like Button, TextBox, CheckBox, so developers can use it to build forms

Solution

  • Decoupling the Sender/Invoker from the Receiver
  • You can keep track of all commands that are executed. Repla, undo
public interface ICommand
{
    void Execute();
}
public class Button
{
    private readonly ICommand command;

    public Button(ICommand command)
    {
        this.command = command;
    }

    public void Click()
    {
        command.Execute();
    }
}
public class CustomerService
{
    public void AddCustomer()
    {
        Console.WriteLine("Add customer");
    }
}
public class AddCustomerCommand : ICommand
{
    CustomerService customerService;

    public AddCustomerCommand(CustomerService customerService)
    {
        this.customerService = customerService;
    }

    public void Execute()
    {
        customerService.AddCustomer();
    }
}

Example Structure

Command Example Structure

Example Code

Editor Example