public interface Command { public void execute();}在大多数情况下,命令是不可变的,并且包含封装了按需执行的单个动作的指令。您可能还具有一个RuntimeCommand,该RuntimeCommand在执行时接受指令,但是根据实现的不同,它会更深入地研究Strategy或Decorator模式。
我个人认为,注意命令的不变上下文非常重要,否则命令将成为建议。例如:
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(); } }); }}我个人不太喜欢命令。以我自己的经验,它们仅适用于框架回调。
如果有帮助,请从隐喻的角度思考命令;受过训练的士兵由其指挥官下达命令,并根据要求执行该命令。



