設計模式實戰---命令模式

定義與類型

設計模式實戰---命令模式

適用場景

設計模式實戰---命令模式

優點

設計模式實戰---命令模式

缺點

設計模式實戰---命令模式

相關模式

備忘錄模式經常結合使用

coding

設計模式實戰---命令模式

設計模式實戰---命令模式

設計模式實戰---命令模式

設計模式實戰---命令模式

設計模式實戰---命令模式

設計模式實戰---命令模式

設計模式實戰---命令模式


典型應用是GUI中的繪圖程序, 用命令模式實現“撤銷”操作.

  • 命令接收者:執行實際任務。
  • 命令者:封裝所有命令者的信息。
  • 發起者:空著一個或者多個命令的順序和執行。
  • 客戶端:創建具體的命令實例
<code>public class DrawInvoker {

//繪製列表
private List<drawpath> drawList = Collections.synchronizedList(new ArrayList<drawpath>());

//重做列表
private List<drawpath> redoList = Collections.synchronizedList(new ArrayList<drawpath>());

//添加一條命令
public void add(DrawPath command) {
redoList.clear();
drawList.add(command);
}

//撤銷操作
public void undo() {
if(drawList.size() >0 ) {
DrawPath undo = drawList.get(drawList.size() - 1);
drawList.remove(drawList.size() - 1); // 把drawList中的最後一條命令刪除掉.
undo.undo();
redoList.add(undo);
}
}
}/<drawpath>/<drawpath>/<drawpath>/<drawpath>/<code>

“撤銷”上一步操作的實現原理是, 首先記錄每一條繪製命令到drawList中, “撤銷”操作就是把最後一條命令從drawList中刪除, 然後把canvas清空, 把drawList中的命令在清空的canvas上再繪製一遍.

本文由博客一文多發平臺 https://openwrite.cn?from=article_bottom 發佈!


分享到:


相關文章: