前言
命令模式是行爲型模式之一,特點是將“請求”封裝成對象,以便使用不同的請求,隊列或者日誌來參數化其他對象。命令模式也支持可撤銷的操作。
餐廳命令模式
角色
顧客、女招待、訂單、快餐廚師。
職責
- 顧客發出訂單請求
- 訂單封裝了準備餐點的請求
- 女招待工作是接收訂單takeOrder(order),調用訂單的orderUp()方法
- 快餐廚師實現創建餐點的所有方法。
命令模式
1.實現過程
2.命令模式類圖
二、智能家電需求
1.角色
角色:遙控器、家用電器(電燈)、動作(打開或關閉)
通過遙控器,控制電燈的動作。
2.要求
電燈和遙控器之間要解耦,不同廠商提供的電器,只需要一個遙控器就可以,之後可以動態添加電器。
三、遙控器打開或關閉燈代碼
1.Light對象
public class Light {
private String name;
public Light(String name){
this.name=name;
}
public void on(){
System.out.println(this.name+"的燈打開了");
}
public void off(){
System.out.println(this.name+"的燈關閉了");
}
}
2.Command接口
命令接口,只有一個方法
public interface Command {
void execute();
}
3.兩個實現Command接口的命令類
這是兩個命令,需要實現command接口,構造器傳入的參數電燈Light是接收者,負責接受請求。
LightOnCommand類 打開燈的命令類
public class LightOnCommand implements Command {
Light light;
public LightOnCommand(Light light){
this.light=light;
}
@Override
public void execute() {
light.on();
}
}
LightOffCommand類 關閉燈的命令類
public class LightOffCommand implements Command {
Light light;
public LightOffCommand(Light light){
this.light=light;
}
@Override
public void execute() {
light.off();
}
}
4.SimpleRemoteControl 遙控器類
它只有一個按鈕和對應的插槽,可以控制一個裝置,Commadn slot 是一個插槽持有的命令,這個命令控制着一個裝置。
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl(){}
public void setCommand(Command command){
slot=command;
}
public void buttonWasPressed(){
slot.execute();
}
}
5.測試類
public class RemoteControlTest {
public static void main(String[] args){
SimpleRemoteControl remote=new SimpleRemoteControl();
Light light=new Light("客廳");
LightOnCommand lightON=new LightOnCommand(light);
LightOffCommand lightOff=new LightOffCommand(light);
remote.setCommand(lightON);
remote.buttonWasPressed();
remote.setCommand(lightOff);
remote.buttonWasPressed();
}
}
運行結果圖
感謝您的訪問!