命令模式:
1.命令模式:按自己的理解,命令模式的優點在於封裝性完好,user在使用命令模式時候只需要知道“功能”而不需瞭解其他,而命令模式的重點在於,把所有的命令事先寫好在一個類(ControlPanel)中,這樣所有的操作都僅對這個(ControlPanel)類執行。
ICommand:所有命令的父類
ProjecterOnCommand 等:命令的具體類
Light 等:命令的具體動作
ControlPanel:控制類,控制命令的動作
2.例子:簡單地模擬控制一間房間的燈的開關。
首先,創建所有命令(command)的父類IComm
package pers.reus.model.command.impl;
public abstract class ICommand {
//抽象方法Execute用來執行命令
public abstract void Execute();
}
接下來創建 開燈(LightOnCommand)和關燈(LightOffCommand)兩個子類
開燈:
package pers.reus.model.command;
import pers.reus.model.command.impl.ICommand;
import pers.reus.model.concreteCommand.Light;
public class LightOnCommand extends ICommand{
//燈的具體類Light
Light light;
//聲明開燈類時,需要對此類設置一個具體的燈類對象Light
public LightOnCommand(Light light){
this.light = light;
}
//Execute調用燈的具體類裏面的"開燈"函數
public void Execute() {
light.TurnOnLight();
}
}
關燈:
<span style="font-size:12px;">package pers.reus.model.command;
import pers.reus.model.command.impl.ICommand;
import pers.reus.model.concreteCommand.Light;
public class LightOffCommand extends ICommand{
//燈的具體類Light
Light light;
//聲明關燈類時,需要對此類設置一個具體的燈類對象Light
public LightOffCommand(Light light){
this.light = light;
}
//Execute調用燈的具體類裏面的"關燈"函數
public void Execute() {
light.TurnOffLight();
}
}</span>
接下來創建 燈 的具體類:
<span style="font-size:12px;">package pers.reus.model.concreteCommand;
//燈 的具體類
public class Light {
//開燈
public void TurnOnLight(){
System.out.println("開燈!");
}
//關燈
public void TurnOffLight(){
System.out.println("關燈!");
}
}</span>
最重要的是這個控制面板(CommandPanel)類:
<span style="font-size:12px;">package pers.reus.model.controlPanel;
import java.util.Hashtable;
import pers.reus.model.command.impl.ICommand;
//CpControlPanel 裏面包括一系列的命令操作
public class CpControlPanel {
//聲明一個Hashtable,用來存放命令代號和命令類
Hashtable ht = new Hashtable();
/**
* cmd是命令代號
* ic是命令類
* 如setCommand("lco",LightOnCommand)表示爲把"開燈類"存入ht,代號爲lco
**/
public void setCommand(String cmd,ICommand ic){
ht.put(cmd,ic);
}
//爲每一個功能都創建特定的函數,調用ExcuteLightOn()就會開燈
public void ExcuteLightOn(){
//從ht裏面通過代號"lco"找到已經存進去的LightOnCommand類,並賦值給ic
ICommand ic = (ICommand) ht.get("lco");
//調用LightOnCommand類的Execute()函數
ic.Execute();
}
public void ExcuteLightOff(){
//從ht裏面通過代號"lcf"找到已經存進去的LightOffCommand類,並賦值給ic
ICommand ic = (ICommand) ht.get("lcf");
//調用LightOnCommand類的Execute()函數
ic.Execute();
}
}</span>
客戶類進行測試:
package pers.reus.model.client;
import pers.reus.model.command.LightOffCommand;
import pers.reus.model.command.LightOnCommand;
import pers.reus.model.concreteCommand.Light;
import pers.reus.model.controlPanel.CpControlPanel;
//客戶類測試
public class CommandPatternClient {
public static void main(String[] args) {
//聲明燈的具體類
Light light = new Light();
//在開燈和關燈類中放入燈的具體對象
LightOnCommand lco = new LightOnCommand(light);
LightOffCommand lcf = new LightOffCommand(light);
//聲明控制面板類
CpControlPanel ccp = new CpControlPanel();
//把開燈,關燈的ICommand類放入hashtable並設定對應的代號
ccp.setCommand("lco",lco);
ccp.setCommand("lcf",lcf);
//調用控制面板類(CpContrilPanel)裏面的開燈函數,進行測試
ccp.ExcuteLightOn();
}
}