写博客是为了个人做笔记,希望大家不要被误导。
命令模式:将请求封装成对象(这里的实现Command接口的类),这可以让你使用不同的请求、队列,或者日志请求来参数化其它对象。命令模式也可以支持撤销操作。
案例:一个遥控器,实现音响(stereo)开、关、调高、调低、撤销操作或者是一系列操作。这些操作是可变的。而且遥控器还可以控制其它电器。采用命令模式,将这些操作封装成对象,它们共同实现一个Command接口(有execute()、undo()方法),遥控器调用这些对象的相应方法。这样让发出请求的对象(遥控器)和执行请求的对象(音响等家电)解耦,被解耦的两者之间用命令对象(Command对象)沟通。
public interface ElectricalAppliance {
public void on();
public void off();
}
public class Stereo implements ElectricalAppliance {
public static final int DOWN = 3;
public static final int MEDIUM = 5;
public static final int UP = 8;
@Override
public void on() {
}
@Override
public void off() {
}
public void turnUp(){};
public void turnMedium(){};
public void turnDown(){};
public void setVolumn(int volumn){};
public int getVolumn(){return 0;};
}
public interface Command {
public void execute();
public void unDo();
}
public class CommandStereoOn implements Command{
Stereo stereo;
@Override
public void execute() {
stereo.on();
stereo.setVolumn(5);
}
@Override
public void unDo() {
stereo.off();
}
}
public class CommandStereoTurnUp implements Command {
Stereo stereo;
int volumn;
public CommandStereoTurnUp(Stereo stereo){
this.stereo = stereo;
}
@Override
public void execute() {
stereo.turnUp();
}
@Override
public void unDo() {
if (stereo.getVolumn() == stereo.UP) stereo.turnUp();
if (stereo.getVolumn() == stereo.MEDIUM) stereo.turnMedium();
if (stereo.getVolumn() == stereo.DOWN) stereo.turnDown();
}
}
public class MacroCommands implements Command {//定义一连串指令
Command[] commands;
@Override
public void execute() {
for (Command command:commands) command.execute();
}
@Override
public void unDo() {
for (Command command:commands) command.unDo();
}
public MacroCommands(Command[] commands){
this.commands = commands;
}
}
public class Nocommand implements Command {
@Override
public void execute() {
}
@Override
public void unDo() {
}
}
public class RemoteControl {
public static final int COUNT_OF_BUTTONS = 3;//遥控器按钮数量
Command command;
Command undoCommand = new Nocommand();//存储上次执行的指令是什么(上次哪个对象执行了excute(),撤销时直接让undoCommand调用undo()
Command[] buttons;
public RemoteControl(){
buttons = new Command[COUNT_OF_BUTTONS];
}
public void pushBotton(int x){//第x个按钮被按下
buttons[x].execute();
undoCommand = buttons[x];
}
public void setCommand(int x,Command command){//设置按钮功能
buttons[x] = command;
}
public void undo(){
undoCommand.unDo();
}
}