命令模式定义如下:将一个请求封装成一个对象,从而使用户可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
适合命令模式的情景如下:程序需要在不同的时刻指定、排列和执行请求;程序需要提供撤销操作;程序需要支持宏操作。
顾名思义,命令模式一定是要有命令发送者、命令接收者。命令发送者负责发送命令;命令接收者负责接收命令并完成具体的工作。例如,老师通知学生打扫卫生,老师是命令发送者,学生是命令接收者。
考虑老师通知学生打扫卫生的程序描述,具体代码如下所示。
1.抽象命令接口ICommand
public interface ICommand {
public void sweep();
}
2.命令接收者Student
public class Student {
public void sweep() {
System.out.println("we are sweeping the floor");
}
}
3.命令发送者Teacher
public class Teacher implements ICommand {
private Student receiver = null;
public Teacher(Student receiver) {
this.receiver = receiver;
}
@Override
public void sweep() {
// TODO Auto-generated method stub
receiver.sweep();
}
}
4.命令请求者Invoke
public class Invoke {
private ICommand command;
public Invoke(ICommand command) {
this.command = command;
}
public void execute() {
command.sweep();
}
}
按普通思路来说:有命令发送者,命令接收者已经足够了,也便于理解。为什么还要有请求者类Invoke呢?普通思路是命令发送者直接作用命令接收者,而命令模式思路是在两者之间增加一个请求类,命令发送者与请求者先作用,请求者再与命令接收者作用。在此过程中,请求者充当一个桥梁的作用。
5.一个简单的测试类Test
public class Test {
public static void main(String[] args) {
Student s = new Student();
Teacher t = new Teacher(s);
Invoke invoke = new Invoke(t);
invoke.execute();
}
}
输出结果:we are sweeping the floor
案例:遥控器控制天花板上的吊扇,它有多种转动速度,当然也允许被关闭。假设吊扇的速度有高、中、低三档。利用命令模式编制功能类和测试类。
1.抽象命令发送者ICommand
public interface ICommand {
public void speed();
}
2.高档速度命令发送者HighSpeedCommand
public class HighSpeedCommand implements ICommand {
private Blower blower;
public HighSpeedCommand(Blower blower) {
this.blower = blower;
}
@Override
public void speed() {
// TODO Auto-generated method stub
blower.highSpeed();
}
}
3.中档速度命令发送者HighSpeedCommand
public class MidSpeedCommand implements ICommand {
private Blower blower;
public MidSpeedCommand(Blower blower) {
this.blower = blower;
}
@Override
public void speed() {
// TODO Auto-generated method stub
blower.midSpeed();
}
}
4.低档速度命令发送者LowSpeedCommand
public class LowSpeedCommand implements ICommand {
private Blower blower;
public LowSpeedCommand(Blower blower) {
this.blower = blower;
}
@Override
public void speed() {
blower.lowSpeed();
}
}
5.电扇命令接收者Blower
public class Blower {
public void highSpeed() {
System.out.println("the blower in HighSpeed!");
}
public void midSpeed() {
System.out.println("the blower in midSpeed!");
}
public void lowSpeed() {
System.out.println("the blower in lowSpeed!");
}
}
6.命令请求者类
public class CommandManager {
private ICommand iCommand;
public CommandManager(ICommand iCommand) {
this.iCommand = iCommand;
}
public void run() {
iCommand.speed();
}
}
7.简单测试类Test
public class Test {
public static void main(String[] args) {
Blower blower = new Blower();
HighSpeedCommand highSpeed = new HighSpeedCommand(blower);
CommandManager manager = new CommandManager(highSpeed);
manager.run();
}
}
输出结果:the blower in HighSpeed!