UML:
1.png
定義:
將某個請求(開機(jī),關(guān)機(jī)氮惯,換臺)封裝成一個對象(TurnOnCommand,TurnOffCommand,ChangeChannelCommand)厌均,從而可用不同的請求實(shí)現(xiàn)客戶端的參數(shù)化( Control control = new Control(on, off, changechannel))
本質(zhì):
將發(fā)出請求的對象(client)請求的真正執(zhí)行者(mytv)解耦棺弊。
角色:
Command: 命令接口,聲明執(zhí)行操作模她。
ConcreateCommand:實(shí)現(xiàn)commmand 命令持有真正的執(zhí)行者侈净。將執(zhí)行者與命令綁定畜侦。TurnOffCommand
Client:創(chuàng)建命令設(shè)定執(zhí)行者旋膳。Client
Invoker:執(zhí)行命令請求验懊。Control
Receiver:命令的執(zhí)行者义图。mytv
(1)命令真正的執(zhí)行者
public class MyTV {
public int channel = 0;
public void turnOff() {
System.out.println("mytv is turn off!!");
}
public void turnOn() {
System.out.println("mytv is turn on!!");
}
public void changeChannel(int channel) {
this.channel = channel;
System.out.println("now tv chaannel is " + channel + "!!");
}
}
(2)命令接口
public interface Command {
public void execute();
}
(3)命令實(shí)現(xiàn)類
public class implements Command {
private MyTV myTV;
public TurnOffCommand(MyTV myTV) {
this.myTV = myTV;
}
@Override
public void execute() {
myTV.turnOff();
}
}
public class TurnOnCommand implements Command {
private MyTV myTV;
public TurnOnCommand(MyTV myTV) {
this.myTV = myTV;
}
@Override
public void execute() {
myTV.turnOn();
}
}
public class ChangeChannelCommand implements Command {
private MyTV myTV;
private int channel;
public ChangeChannelCommand(MyTV myTV, int channel) {
this.myTV = myTV;
this.channel = channel;
}
@Override
public void execute() {
myTV.changeChannel(channel);
}
}
(3)控制器
public class Control {
public Command oncommand, offcommand, changecommand;
public Control(Command oncommand, Command offcommand, Command changecommand) {
this.oncommand = oncommand;
this.offcommand = offcommand;
this.changecommand = changecommand;
}
public void turnOn() {
this.oncommand.execute();
}
public void turnOff() {
this.offcommand.execute();
}
public void changeChannel() {
this.changecommand.execute();
}
}
(4)測試類
public class Client {
public static void main(String[] args) {
//接受者
MyTV myTV = new MyTV();
//開機(jī)命令
Command on = new TurnOnCommand(myTV);
//關(guān)機(jī)命令
Command off = new TurnOffCommand(myTV);
//換臺
Command changechannel = new ChangeChannelCommand(myTV, 9);
//命令控制對象
Control control = new Control(on, off, changechannel);
control.turnOn();
control.turnOff();
control.changeChannel();
}
}