命令模式
命令模式屬于行為模式。如你的上級領導指派給你的A,B,C三項任務。讓你做A,你就做A,讓你做B就做B。指哪打哪。
外部的人對于你和你的領導來說,知道你的領導派發(fā)了ABC任務給你,你也完成ABC任務,任務具體是怎么完成的外部的人并不需要關心。
使用場景
- 某一對象有一系列的事物操作
- 具有抽象行為的動作,支持多種類型的操作
代碼示例
大學的新生入學都會進行軍訓,軍訓的項目有正步,齊步,軍姿等等... 而這一系列的內(nèi)容都是由教官下發(fā)命令,所有的同學進行執(zhí)行。
- 常規(guī)實現(xiàn)方式
只需要封裝一個具體的軍訓類管理即可,直接調(diào)用即可
public class MilitaryTraining {
public void march() {
System.out.print("軍訓齊步");
}
public void goose() {
System.out.print("軍訓正步");
}
}
- 命令模式
(一)命令接口做什么
public interface Command {
void doSomothing();//具體做什么
}
(二)具體的命令
齊步命令:
public class MarchCommand implements Command {
private MilitaryTraining militaryTraining;
public MarchCommand(MilitaryTraining militaryTraining1) {
this.militaryTraining = militaryTraining1;
}
@Override
public void doSomothing() {
if (militaryTraining!=null){
militaryTraining.march();
}
}
}
正步命令:
public class GooseCommand implements Command {
private MilitaryTraining militaryTraining;
public GooseCommand(MilitaryTraining militaryTraining1) {
this.militaryTraining = militaryTraining1;
}
@Override
public void doSomothing() {
if (militaryTraining != null) {
militaryTraining.goose();
}
}
}
(三)命令控制的管理器
public class CommandController {
private GooseCommand gooseCommand;
private MarchCommand marchCommand;
public void setGooseCommand(GooseCommand gooseCommand) {
this.gooseCommand = gooseCommand;
}
public void setMarchCommand(MarchCommand marchCommand) {
this.marchCommand = marchCommand;
}
public void marchCommadn(){
if(marchCommand!=null){
marchCommand.doSomothing();
}
}
public void gooseCommand(){
if(gooseCommand!=null){
gooseCommand.doSomothing();
}
}
}
(四)調(diào)用方式
- 常規(guī)方式
MilitaryTraining militaryTraining=new MilitaryTraining();
militaryTraining.goose();//正步
militaryTraining.march();//齊步
- 命令模式
//采用命令模式調(diào)用
/**
* 優(yōu)點:命令模式耦合度更低,擴展性更強,維護方便,
* 可對命令進行組合使用
* 對新的命令擴展更容易
*
* 缺點:命令類很多,對基礎技術要求較高,否則難于閱讀代碼。
*/
MilitaryTraining militaryTraining1 = new MilitaryTraining();
GooseCommand gooseCommand = new GooseCommand(militaryTraining1);
MarchCommand marchCommand = new MarchCommand(militaryTraining1);
CommandController commandController = new CommandController();
commandController.setGooseCommand(gooseCommand);
commandController.setMarchCommand(marchCommand);
commandController.gooseCommand();
commandController.marchCommadn();
(五)顯示結果
軍訓正步
軍訓齊步
軍訓正步
軍訓齊步
總結
優(yōu)點:
- 耦合度低,命令可控,可組合同時完成或者順序完成
缺點:
- 類太多,簡單的行為命令反而復雜
明顯看出上面的調(diào)用方式,傳統(tǒng)方式2行代碼就可以解決的問題,使用命令模式卻多了很多類和代碼,還不如不用設計模式清晰簡單,為什么會這樣呢?
因為上述的命令以及行為操作很簡單,因此對于簡單的行為操作命令,個人建議按照傳統(tǒng)方式使用書寫就好,過度使用設計模式反而令人不易理解,類的增加也極其迅速。
但是命令模式的好處是對于復雜的行為命令,可以更好的降低耦合度,將命令發(fā)起方與執(zhí)行方隔離,只需要發(fā)起命令,由誰完成,怎么樣完成都不需要知道。