Using Command Design pattern

后端 未结 6 1133
误落风尘
误落风尘 2020-11-27 18:26

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

6条回答
  •  一向
    一向 (楼主)
    2020-11-27 18:41

    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.

提交回复
热议问题