设计模式命令模式

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理