设计模式——命令模式

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

定义

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

![图片上传中...]测试

clipboard.png

类图

clipboard.png

代码演示

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();
    }
}

测试this

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


remote.setCommand(lightOn);
remote.buttonWasPressed();
相关文章
相关标签/搜索