Sobes.tech
Junior — Middle

What is the purpose and application of the Command pattern in programming?

sobes.tech AI

Answer from AI

The Command pattern is designed to encapsulate a request or operation as a separate object. This allows the sender of the command to be decoupled from its executor, and also enables features such as deferred execution, undo operations, logging, and command queues.

The pattern is useful when you need to:

  • Delay the execution of an operation.
  • Implement undo or redo functionality.
  • Create complex sequences of operations.
  • Simplify extending functionality without modifying existing code.

Example in Java:

// Command interface
interface Command {
    void execute();
}

// Concrete command
class LightOnCommand implements Command {
    private Light light;
    public LightOnCommand(Light light) { this.light = light; }
    public void execute() { light.turnOn(); }
}

// Receiver
class Light {
    void turnOn() { System.out.println("Light is on"); }
}

// Client
public class RemoteControl {
    private Command command;
    public void setCommand(Command command) { this.command = command; }
    public void pressButton() { command.execute(); }
}