Java行為型模式中命令模式分析
一.介紹
命令模式(Command Pattern)屬于行為型模式。請求以命令的形式包裹在對象中,并傳給調(diào)用對象。調(diào)用對象尋找可以處理該命令的合適的對象,并把該命令傳給相應(yīng)的對象,該對象執(zhí)行命令,執(zhí)行順序是調(diào)用者→命令→接收者,實現(xiàn)調(diào)用者(Invoker)與接收者(Receiver)解耦
二.場景約束
設(shè)計一個文本編輯器(TextField),支持復(fù)制、插入以及撤銷操作
三.UML類圖
四.示意代碼
業(yè)務(wù)代碼
//抽象命令 public interface Command { void execute(); void undo(); } //調(diào)用者 class Invoker{ private Command command; public Invoker(Command command) { this.command = command; } public void setCommand(Command command) { this.command = command; } public void call(){ command.execute(); command.undo(); } } //具體命令 class insertCommand implements Command { private TextField textField; private String insertStr = "insertStr"; public insertCommand(TextField textField) { this.textField = textField; } @Override public void execute() { textField.text += insertStr; System.out.println(textField.text); } @Override public void undo() { textField.text = textField.text.substring(0, textField.text.length() - insertStr.length()); System.out.println(textField.text); } } //具體命令 class CopyCommand implements Command { private TextField textField; public CopyCommand(TextField textField) { this.textField = textField; } @Override public void execute() { textField.text += textField.text; System.out.println(textField.text); } @Override public void undo() { textField.text = textField.text.substring(0, textField.text.length() / 2); System.out.println(textField.text); } } //接收者 class TextField { public String text = "text"; }
客戶端
public class Client { public static void main(String[] args) { Invoker invoker = new Invoker(new CopyCommand(new TextField())); invoker.call(); } }
五.優(yōu)點
優(yōu)點
- 新增、刪除命令非常方便
- 符合開閉原則
- 命令可以組合,同時支持命令的撤銷和恢復(fù)
- 命令可以增加統(tǒng)一功能:日志、權(quán)限
- 調(diào)用者與接收者解耦
六.在JDK中的應(yīng)用
java.lang.Runnable是一個典型的命令模式,Runnable充當(dāng)抽象命令的角色,Thread充當(dāng)調(diào)用者的角色,而接收者的角色是開發(fā)者自己定義的
//具體命令 class ConcreteCommand implements Runnable{ private Receiver receiver; public ConcreteCommand(Receiver receiver) { this.receiver = receiver; } @Override public void run() { receiver.execute(); } } //接收者 class Receiver{ public void execute(){ System.out.println("執(zhí)行邏輯"); } }
到此這篇關(guān)于Java行為型模式中命令模式分析的文章就介紹到這了,更多相關(guān)Java命令模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺析我對 String、StringBuilder、StringBuffer 的理解
StringBuilder、StringBuffer 和 String 一樣,都是用于存儲字符串的。這篇文章談?wù)勑【帉tring、StringBuilder、StringBuffer 的理解,感興趣的朋友跟隨小編一起看看吧2020-05-05Java虛擬機JVM性能優(yōu)化(一):JVM知識總結(jié)
這篇文章主要介紹了Java虛擬機JVM性能優(yōu)化(一):JVM知識總結(jié),本文是系列文章的第一篇,后續(xù)篇章請繼續(xù)關(guān)注腳本之家,需要的朋友可以參考下2014-09-09SpringBoot默認使用HikariDataSource數(shù)據(jù)源方式
這篇文章主要介紹了SpringBoot默認使用HikariDataSource數(shù)據(jù)源方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10SpringMVC利用dropzone組件實現(xiàn)圖片上傳
這篇文章主要介紹了SpringMVC利用dropzone組件實現(xiàn)圖片上傳,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02