使用命令设计模式 [英] Using Command Design pattern
问题描述
public interface Command {
public void execute();
}
在大多数情况下,命令是不可变的,包含封装单个操作的指令这是按需执行的。您可能还有一个RuntimeCommand在执行时接受指令,但是根据实施情况,您可以深入了解策略或装饰器模式。
在我自己的看来,我认为非常重要的是注意命令的不变的上下文,否则命令成为一个建议。例如:
public final class StopServerCommand实现Command {
private final Server server;
public StopServerCommand(服务器服务器){this.server = server; }
public void execute(){
if(server.isRunning())server.stop();
}
}
public class Application {
// ...
public void someMethod(){
stopButton.addActionListener ActionListener(){
public void actionPerformed(Event e){
stopCommand.execute();
}
});
}
}
我个人并不喜欢命令。在我自己的经验中,他们只对框架回调有效。
如果有帮助,想一个隐喻意义上的命令;训练有素的士兵由他/她的指挥官指挥,并且要求士兵执行这个命令。
Can any one explain with simple example of Command Pattern. I refer in internet but i got confused.
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.
这篇关于使用命令设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!