設計模式學習筆記(十四)—Command模式

來源:互聯網
上載者:User

一、Command模式定義:

將一個請求封裝為一個對象,從而使你不同的請求對客戶進行參數化;對請求排隊或記錄請求日誌,以及支援可撤銷的操作。

二、模式解說

Commad模式是一種對象行為模式,它可以對寄件者(sender)和接收者(receiver)完全解耦(decoupling)。("寄件者" 是請求操作的對象,"接收者" 是接收請求並執行某操作的對象。有了 "解耦",寄件者對接收者的介面一無所知。)這裡,"請求"(request)這個術語指的是要被執行的命令。Command模式還讓我們可以對 "何時" 以及 "如何" 完成請求進行改變。因此,Command模式為我們提供了靈活性和可擴充性。

三、結構圖

Command模式結構圖如下:

四、怎麼使用?

1)定義一個Command介面,介面中有一個統一的方法,這就是將請求/命令封裝為對象。

2)定義具體不同命令類ConcreteCommand實現Command介面。

3)定義一個命令的調用角色Invoker。

4)定義一個命令執行狀態的接收者Receiver(非必須)。

五、一個例子

class Document{
public void display(){
  System.out.println("顯示文檔內容");
}
public void undo(){
  System.out.println("撤銷文檔內容");
}
public void redo(){
  System.out.println("重做文檔內容");
}
}
interface DocumentCommand{
public void execute();
}
class DisplayCommand implements DocumentCommand{
private Document document;
public DisplayCommand(Document doc){
  document=doc;
}
public void execute() {

  document.display();
}
}
class UndoCommand implements DocumentCommand{
   private Document document;
   public UndoCommand(Document doc){
   document=doc;
   }
public void execute() {
  document.undo();

}
}
class RedoCommand implements DocumentCommand{
private Document document;
public RedoCommand(Document doc){
  document=doc;
}
public void execute(){
  document.redo();
}
}
class DocumentInvoker{
private DisplayCommand _dcmd;
private UndoCommand _ucmd;
private RedoCommand _rcmd;
public DocumentInvoker(DisplayCommand dcmd,UndoCommand ucmd,RedoCommand rcmd){
  this._dcmd=dcmd;
  this._ucmd=ucmd;
  this._rcmd=rcmd;
}
public void display(){
  _dcmd.execute();
}
public void undo(){
  _ucmd.execute();
}
public void redo(){
  _rcmd.execute();
}
}
public class CommandTest {

public static void main(String[] args) {
  Document doc=new Document();
  DisplayCommand display=new DisplayCommand(doc);
  UndoCommand undo=new UndoCommand(doc);
  RedoCommand redo=new RedoCommand(doc);
  DocumentInvoker invoker=new DocumentInvoker(display,undo,redo);
  invoker.display();
  invoker.undo();
  invoker.redo();

}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.