設計模式學習(六)命令模式

2021-10-05 05:40:23 字數 1866 閱讀 6122

將「請求」封裝成物件,以便使用不同的請求、佇列或者日誌來引數化其他物件。命令模式也支援可撤銷的操作。

設計遙控器,分別裝有7組「開」與「關」按鈕來控制多個裝置,還需要支援整體的撤銷功能。

1.首先,我們需要實現命令的介面

public inte***ce command
2.分別實現開燈、關燈、開關電風扇等命令

public class lightoffcommand implements command

@override

public void execute()

@override

public void undo()

}

public class ceilingfanoffcommand implements command 

@override

public void execute()

@override

public void undo()

}

3.如果不滿足單一命令呼叫,我們完全可以自定義命令

public class macrocommand implements command

//呼叫所有命令的執行

@override

public void execute()

}@override

public void undo()

}}

4.實現遙控器

public class remotecontrol 

undocommand = new nocommand();

}public void setcommands(int slot, command oncommand, command offcommand)

public void onbuttonwaspushed(int slot)

public void offbuttonwaspushed(int slot)

public void undobuttonwaspushed()

}

5.測試

public class test ;

command partyoff = ;

macrocommand macrooncommand = new macrocommand(partyon);

macrocommand macrooffcommand = new macrocommand(partyoff);

//將命令載入到控制中

remotecontrol.setcommands(0, livinglighton, livinglightoff);

remotecontrol.setcommands(1, kitchenlighton, kitchenlightoff);

remotecontrol.setcommands(2, fanoncommand, fanoffcommand);

remotecontrol.setcommands(3, macrooncommand, macrooffcommand);

//測試

remotecontrol.offbuttonwaspushed(0);

remotecontrol.onbuttonwaspushed(1);

remotecontrol.undobuttonwaspushed();

remotecontrol.offbuttonwaspushed(1);

remotecontrol.onbuttonwaspushed(2);

}}

設計模式學習筆記(六) 命令模式

同系列文章 1.設計模式學習筆記 一 策略模式 2.設計模式學習筆記 二 觀察者模式 3.設計模式學習筆記 三 裝飾者模式 4.設計模式學習筆記 四 工廠模式 5.設計模式學習筆記 五 單件模式 又是嶄新的一日,今天我來學習命令模式 gogogo 看了一下書,好多頁呀哈哈哈,有得擼 將 請求 封裝成...

設計模式學習筆記(六) 命令模式

定義 將 請求 封裝為物件,以便使用不同的請求,佇列或者日誌來引數化其他物件。命令模式也支援可撤銷的操作 uml類圖 command 為所有的命令宣告了乙個介面,呼叫命令物件的execute方法即可讓接收者進行相關動作。concretecommand 定義了動作和接收者之間的繫結關係,呼叫者只需要呼...

設計模式(六) 命令模式

命令模式 將請求封裝成物件,以便使用不同的請求 佇列或者日誌來引數化其他物件。命令模式也支援可撤銷的操作。public inte ce commandpublic class light public void off public class lightoncommand implements c...