views:

292

answers:

1

Hi all,

Can any one explain with simple example of Command Pattern. I refer in internet but i got confused.

Thanks, Ravi

+6  A: 
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.

Droo
@Droo, follow-up to your "don't really like" - they're actually a very natural implementation for things like abstracting device control. For example, I used to have to drive a variety of cameras (that all use different serial protocols) using a common joystick. It was very helpful to have a Command for "Pan", another for "Zoom", etc.
Bob Cross
or java.lang.Runnable
arjan
@Droo: can you explain with simple example?
Ravi K Chowdary