日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

[译]Java 设计模式之命令

發布時間:2025/7/14 java 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [译]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 设计模式之命令的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。