命令模式:可将“动作的请求者”从”对象的执行者“对象中解耦;将”发出请求的对象”和”接受与执行这些请求的对象“分割开来。
实例: 共有三个类 一个接口 一个测试类。三个类中 一个是执行者 一个是命令 一个是动作请求者(控制器)
/**
* 命令接口 所有命令都实现该接口
* 命令模式:将请求封装成对象,以便使用不同的请求、
* 队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
* 用途:队列 日志
* @下午08:51:37
* @author ASUS
*/
public interface Command {
public void excute();
}
/**
* 装置 灯
* 命令执行者
* @下午08:50:02
* @author ASUS
*/
public class Light {
public void on(){
System.out.println("Light is on");
}
public void off(){
System.out.println("Light is off");
}
}
/**
* 控制灯开的命令
* @下午08:56:41
* @author ASUS
*/
public class LightOnCommand implements Command{
Light light;
public LightOnCommand(Light light){
this.light=light;
}
@Override
public void excute() {
light.on();
}
}
/**
* 简单的控制器
* @下午08:59:27
* @author ASUS
*/
public class SimpleRemoteControl {
Command command;
public SimpleRemoteControl(){
}
public void setCommand(Command command){
this.command=command;
}
public void buttonWasPressed(){
command.excute();
}
摘自 《Head First 设计模式》pdf 212-254 书 192-232