您的位置:首页 > 其它

设计模式学习笔记十五:命令模式

2015-08-25 23:34 351 查看

介绍

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

UML结构图:



场景模拟

本例是模拟实现一个遥控器。

代码实现

1.先模拟两个真正干活的对象,即invoker:

public class Light{
public void on() {
System.out.println("light is on");
}
public void off() {
System.out.println("light is off");
}
}

public class TV {
public void on() {
System.out.println("TV is on");
}
public void off() {
System.out.println("TV is off");
}
}

2.定义统一命令调用接口,即Command(刚开始用Runnable来着,偷懒:]):

public interface Command {
public void execute();
}

3.定义开关命令,统一实现Command接口,即ConcreteCommand:

public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}

public class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.off();
}
}

4.定义操作控制对象,即Receiver:

public class RemoteControl {
Command[] onCommands;
Command[] offCommands;
public RemoteControl() {
onCommands = new Command[2];
offCommands = new Command[2];
}
public void setOnCommand(int slot, Command onCommand, Command offCommand) {
onCommands[slot] = onCommand;
offCommands[slot] = offCommand;
}
public void onButtonWasPushed(int slot) {
onCommands[slot].execute();
}
public void offButtonWasPushed(int slot) {
offCommands[slot].execute();
}

}

5.调用,即Client:

public class RemoteLoader {
public static void main(String[] args) {
RemoteControl control = new RemoteControl();
Light light = new Light();
TV tv = new TV();

// 加载命令
control.setOnCommand(0, new LightOnCommand(light), new LightOffCommand(light));
control.setOnCommand(1, new TVOnCommand(tv), new TVOffCommand(tv));

// 执行命令
control.onButtonWasPushed(0);
control.offButtonWasPushed(0);

System.out.println();

control.onButtonWasPushed(1);
control.offButtonWasPushed(1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: