一、命令模式
将“请求”封装成对象,以便使用不同的请求,队列或者日志来参数化其他对象。命令模式也支持可撤销的操作
二、设计原则
多用组合,少用继承
三、代码实现
1、Client
package com.oyhp.client;
import com.oyhp.command.LightOffCommand;
import com.oyhp.command.LightOnCommand;
import com.oyhp.invoker.SimpleRemoteControl;
import com.oyhp.receiver.Light;
//相当于客户
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light();
//开灯操作
LightOnCommand lightOn = new LightOnCommand(light);
remote.setCommand(lightOn);
remote.buttonWasPressed();
//关灯操作
LightOffCommand lightOff = new LightOffCommand(light);
remote.setCommand(lightOff);
remote.buttonWasPressed();
}
}
2、Invoker
package com.oyhp.invoker;
import com.oyhp.command.Command;
//遥控器
public class SimpleRemoteControl {
Command slot; //组合
public SimpleRemoteControl(){
}
public void setCommand(Command command){
slot = command;
}
public void buttonWasPressed(){
slot.execute();
}
}
3、Receiver
package com.oyhp.receiver;
public abstract class Receiver {
public abstract void on();
public abstract void off();
}
package com.oyhp.receiver;
public class Light extends Receiver{
private String name;
public Light() {
name = "电灯";
System.out.println(name);
}
@Override
public void on() {
// TODO Auto-generated method stub
System.out.println("开");
}
@Override
public void off() {
// TODO Auto-generated method stub
System.out.println("关");
}
}
4、Command
package com.oyhp.command;
//命令
public interface Command {
public void execute();
}
package com.oyhp.command;
import com.oyhp.receiver.Light;
//电灯-关-命令
public class LightOffCommand implements Command{
Light light;
public LightOffCommand(Light light) {
this.light = new Light();
}
@Override
public void execute() {
light.off();
}
}
package com.oyhp.command;
import com.oyhp.receiver.Light;
//电灯-开-命令
public class LightOnCommand implements Command{
Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
四、类图
五、总结
命令模式把每一个操作命令都封装成对象,比如开关灯操作,通过调用者来实现具体的操作,调用者不需要知道如何实现开关操作,只需要“执行”命令就行,从而达到解耦的操作,本章没有演示撤销和party模式。