[译]Java 设计模式之命令
2015-01-10 11:51
405 查看
(文章翻译自Java Design Pattern: Command)
命令设计模式在进行执行和记录的时候需要一个操作及其参数和封装在一个对象里面。在下面的例子中,命令是一个操作,它的参数是一个Computer,而且他们被封装在一个Switch中。
从另外一个视角来看,命令模式有四个部分:command,recevier,invoker和client。在这个例子中,Switch是invoker,Computer是receiver。一个具体的Command需要一个receiver对象而且调用receiver的方法。invok儿使用不同的具体Command。Client决定对于receiver去使用哪个command.
命令设计模式类图
Java命令模式例子
命令设计模式在进行执行和记录的时候需要一个操作及其参数和封装在一个对象里面。在下面的例子中,命令是一个操作,它的参数是一个Computer,而且他们被封装在一个Switch中。
从另外一个视角来看,命令模式有四个部分:command,recevier,invoker和client。在这个例子中,Switch是invoker,Computer是receiver。一个具体的Command需要一个receiver对象而且调用receiver的方法。invok儿使用不同的具体Command。Client决定对于receiver去使用哪个command.
命令设计模式类图
Java命令模式例子
package designpatterns.command; import java.util.List; import java.util.ArrayList; /* The Command interface */ interface Command { void execute(); } // in this example, suppose you use a switch to control computer /* The Invoker class */ class Switch { private List<Command> history = new ArrayList<Command>(); public Switch() { } public void storeAndExecute(Command command) { this.history.add(command); // optional, can do the execute only! command.execute(); } } /* The Receiver class */ class Computer { public void shutDown() { System.out.println("computer is shut down"); } public void restart() { System.out.println("computer is restarted"); } } /* The Command for shutting down the computer*/ class ShutDownCommand implements Command { private Computer computer; public ShutDownCommand(Computer computer) { this.computer = computer; } public void execute(){ computer.shutDown(); } } /* The Command for restarting the computer */ class RestartCommand implements Command { private Computer computer; public RestartCommand(Computer computer) { this.computer = computer; } public void execute() { computer.restart(); } } /* The client */ public class TestCommand { public static void main(String[] args){ Computer computer = new Computer(); Command shutdown = new ShutDownCommand(computer); Command restart = new RestartCommand(computer); Switch s = new Switch(); String str = "shutdown"; //get value based on real situation if(str == "shutdown"){ s.storeAndExecute(shutdown); }else{ s.storeAndExecute(restart); } } }
相关文章推荐
- 戏说java设计模式中的命令模式
- java设计模式_命令模式
- java设计模式_命令模式 两个不同风格的实现
- java设计模式----command模式(命令模式)
- java 设计模式-行为模式之命令模式
- Java设计模式-之Command命令模式
- java 设计模式学习笔记十二 command命令设计模式
- java设计模式_命令模式 两个不同风格的实现
- Java设计模式八:命令模式(Command)
- Java设计模式八:命令模式(Command)
- Java设计模式 Design Pattern:命令模式 Command Pattern
- Java设计模式——命令模式
- java软件体系设计模式----命令
- JAVA设计模式—命令模式(Command)
- java设计模式之Command(菜单命令)
- Java设计模式 Design Pattern:命令模式 Command Pattern
- JAVA设计模式九--Command(命令模式)
- java设计模式之命令模式Command
- java设计模式之命令模式
- 设计模式(十四)----- 命令模式(Command)----(JAVA版)