Sobes.tech
Junior — Middle

Can you give an example when the command pattern is used in code?

sobes.tech AI

Answer from AI

The "Command" pattern is used when you need to encapsulate a request as an object, allowing you to parameterize objects with operations, queue operations, log them, or support undo.

Example in Java: implementing a button that performs different actions.

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

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

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

// Invoker
class RemoteControl {
    private Command slot;
    void setCommand(Command command) { slot = command; }
    void pressButton() { slot.execute(); }
}

// Usage
public class Client {
    public static void main(String[] args) {
        Light light = new Light();
        Command lightOn = new LightOnCommand(light);
        RemoteControl remote = new RemoteControl();
        remote.setCommand(lightOn);
        remote.pressButton(); // Output: Light is on
    }
}

This approach allows separating the object that invokes the operation from the object that performs it.