《Head First设计模式》笔记整理...欢迎交流...

定义

将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其它对象,命令模式也支持可撤销的操作。

![图片上传中...]

类图

代码演示

public interface Command {    public void execute();} public class LightOnCommand implement Command {    Light light;        public LightOnCommand(Light light) {        this.light = light;    }        public void execute() {        light.on(); //execute方法调用接收对象的on方法    }}//invoker请求者public class SimpleRemoteControl {    Command slot;        public SimpleRemoteControl();        public void setCommand(Command slot) {        this.slot = slot;    }        public void buttonWasPressed() {        slot.execute();    }}

测试

SimpleRemoteControl remote = new SimpleRemoteControl();Light xx = new Light();LightOnCommand lightOn = new LightOnCommand(buttonWasPressed);remote.setCommand(lightOn);remote.buttonWasPressed();