[译]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 设计模式之命令的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 好网站
- 下一篇: GoldenGate 配置extract