[译]Java 设计模式之命令
生活随笔
收集整理的这篇文章主要介绍了
[译]Java 设计模式之命令
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
(文章翻译自Java Design Pattern: Command)
命令设计模式在进行执行和记录的时候需要一个操作及其参数和封装在一个对象里面。在下面的例子中,命令是一个操作,它的参数是一个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 situationif(str == "shutdown"){s.storeAndExecute(shutdown);}else{s.storeAndExecute(restart);}} }转载于:https://www.cnblogs.com/zhangminghui/p/4214667.html
总结
以上是生活随笔为你收集整理的[译]Java 设计模式之命令的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 好网站
- 下一篇: 笔记:编写高质量代码 改善Java程序的