Sobes.tech
Junior — Middle

What existing programming approaches can be compared to the Command pattern?

sobes.tech AI

Answer from AI

The Command pattern can be compared to several programming approaches that also encapsulate actions or operations for flexible management:

  • Callback — allows passing a function as a parameter for deferred execution, similar to encapsulating a command.
  • Functional objects (functional interfaces in Java) — objects implementing a single method, which can act as commands.
  • Strategy — encapsulates an algorithm, similar to Command, but focuses on selecting an algorithm rather than executing a specific operation.
  • Event-driven programming — events and handlers can be viewed as commands that execute in response to an event.

Example of Command in Java:

interface Command {
    void execute();
}

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

class Light {
    void on() { System.out.println("Light is ON"); }
}

// Usage
Light light = new Light();
Command switchUp = new LightOnCommand(light);
switchUp.execute();