定义
命令模式将“请求”封装成对象,以便使用不同的请求、队列、日志来参数化其他对象,命令模式也支持撤销的操作。
代码demo
命令接口
public interface Command {
public void execute();
}
具体执行的命令
public class BackCommand implements Command{
public void execute() {
System.out.println("back now");
}
}
public class LightCommand implements Command{
public void execute() {
System.out.println("light on");
}
}
客户类
public class SimpleRemoteControl {
Command comm;
public void setComm(Command comm) {
this.comm = comm;
}
public void preedRemote(){
comm.execute();
}
}
单元测试
public class Unittest {
public static void main(String[] args) {
Command comm=new LightCommand();
Command comm2 = new BackCommand();
SimpleRemoteControl con = new SimpleRemoteControl();
con.setComm(comm);
con.setComm(comm2);
con.preedRemote();
}
}
代码解析
命令模式将发出请求的对象和执行请求的对象解耦。
在被解耦的两者之间是通过命令对象进行沟通的,命令对象封装了接受者和一个活一组对象