命令模式将“请求”封装成对象,实现请求调用者和请求接收者之间的解耦。
public class Light {
String location = "";
public Light(String location) {
this.location = location;
}
public void on() {
System.out.println(location + " light is on");
}
public void off() {
System.out.println(location + " light is off");
}
}
public interface Command {
public void execute();
}
public class LightOnCommand implements Command {
Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.on();
}
public void undo() {
light.off();
}
}
public class LightOffCommand implements Command {
Light light;
public LightOffCommand(Light light) {
this.light = light;
}
public void execute() {
light.off();
}
public void undo() {
light.on();
}
}
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl() {}
public void setCommand(Command command) {
slot = command;
}
public void buttonWasPressed() {
slot.execute();
}
public void undoButtonWasPushed(){
slot.undo();
}
}
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light("Living room");
LightOnCommand lightOn = new LightOnCommand(light);
LightOffCommand lightOff = new LightOffCommand(light);
remote.setCommand(lightOn);
remote.buttonWasPressed();
remote.undoButtonWasPushed();
remote.setCommand(garageOpen);
remote.buttonWasPressed();
}
}
分享到:
相关推荐
设计模式之命令模式 设计模式之命令模式代码 设计模式之命令模式代码
面向对象分析与设计 设计模式之命令模式 面向对象分析与设计 设计模式之命令模式
文章:http://blog.csdn.net/hailushijie/article/details/8719772
23种设计模式之命令模式对命令模式进行了简单的介绍,并附带了例子程序,和大家分享
设计模式之命令模式详解(内附有例子,无源码),2个文件打包在一起上传
java设计模式之命令模式,通过实际生活例子说明命令模式的原理
Java设计模式之命令模式/Java函数式编程 笔记
设计模式这命令模式的Java实现版本和UML设计类图
命令模式(Command) 用意:把一个请求封装到一个对象中,把发出命令和执行命令的责任分开,委派给不同的对象实现。
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可取消的操作。
本文实例讲述了JS设计模式之命令模式概念与用法。分享给大家供大家参考,具体如下: 客户创建命令;调用者执行该命令;接收者在命令执行时执行相应操作 简单命令对象一般用来消除二个对象(调用者和接收者)之间的...
将《Head First 设计模式》(中文版)按章节进行了分割,每章一个文件,方便大家下载。
命令模式 一个服务可以输出四种符号“A,B,C,D”,现在有多个用户要调用这个服务输出不同的字符,每调用一次输出一个字符,请用命令模式实现一个队列缓冲,用户直接向缓冲中填写命令,服务程序负责循环从队列中取出...