Skip to content
Advertisement

Using Command Design pattern

Can anyone explain with a simple example the Command Pattern? I tried searching on the internet, but I got confused.

Advertisement

Answer

public interface Command {
   public void execute();
}

For the most part, commands are immutable and contain instructions that encapsulate a single action that is executed on demand. You might also have a RuntimeCommand that accepts instructions upon execution, but this delves more into the Strategy or Decorator Patterns depending on the implementations.

In my own opinion, I think it’s very important to heed the immutable context of a command otherwise the command becomes a suggestion. For instance:

public final class StopServerCommand implements Command {
    private final Server server;

    public StopServerCommand(Server server) { this.server = server; }

    public void execute() {
        if(server.isRunning()) server.stop();
    }
}

public class Application {
    //...
    public void someMethod() {
        stopButton.addActionListener(new ActionListener() {
            public void actionPerformed(Event e) {
                 stopCommand.execute();
            }
        });
    }
}

I personally don’t really like commands. In my own experience, they only work well for framework callbacks.

If it helps, think of a command in a metaphorical sense; a trained soldier is given a command by his/her commanding officer, and on demand the soldier executes this command.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement