Java命令模式,Java命令模式是将“请求”封装成对象,以便使用不同的请求。
Invoker是调用者对象相当于遥控器,Invoker和Receiver(Receiver相当于一个提供设备的一方,比如:电灯,电灯有开和关的命令)之间通过Command接口进行解耦,ConcreteCommand实现Command接口,里面接收Receiver的对象实现相应的操作。
命令模式,还可以在请求队列、连接池、日志和支持撤销的操作中使用,请求者的请求可以放在队列中,由另外的线程取走执行。
<pre name="code" class="java">public interface Command{
public void execute();
public void undo();
}
public class Invoker{//相当于遥控器
//List<Command> cList = new LinkedList<Command>();
Command[] onCommand= new Command[4];
Command[] offCommand= new Command[4];
public void set(int num,Command c1,Command c2){
if(num<4&&num>=0){
onCommand[num] = c1;
offCommand[num]=c2;
}
else System.out.println("遥控器按钮受限!");
}
public void on(int num){
if(num<4&&num>=0)
onCommand[num].execute();
else System.out.println("不支持此命令:"+num);
}
public void off(int num){
if(num<4&&num>=0)
offCommand[num].execute();
else System.out.println("不支持此命令:"+num);
}
}
</pre><pre>
public class Light{
public void lightOn(){
System.out.println("---The light is on!");
}
public void lightOff(){
System.out.println("---The light is off!");
}
}
public class LightOff implements Command{
Light light;
public LightOff(Light light){
this.light = light;
}
public void execute(){
light.lightOff();
}
public void undo(){
light.lightOn();
}
}
public class LightOn implements Command{
Light light;
public LightOn(Light light){
this.light = light;
}
public void execute(){
light.lightOn();
}
public void undo(){
light.lightOff();
}
}
public class NoCommand implements Command{
@Override
public void execute() {
// TODO Auto-generated method stub
}
@Override
public void undo() {
// TODO Auto-generated method stub
}
}
public class User {
/**
* @param args
*/
public static void main(String[] args) {
Light light =new Light();
//电灯的关和开
LightOn lightOn = new LightOn(light);
LightOff lightOff = new LightOff(light);
//空命令
NoCommand noCommand = new NoCommand();
Invoker control = new Invoker();//遥控器
control.set(0,lightOn,lightOff);
control.set(1,noCommand,noCommand);
//执行遥控器上面的操作
control.on(0);//开电灯
control.off(0);//关电灯
control.on(1);//开电灯
control.off(1);//关电灯
}
}