通过调用者发送指令,接受者接受指令并执行指令;
Http请求就是一种典型的命令模式
public interface Command { //执行命令 public void execute(); //撤销命令 public void undo(); }
public class LightOnCommand implements Command { // 聚合LightReceiver List<LightReceiver> lights; public LightOnCommand(List<LightReceiver> lights) { this.lights = lights; } @Override public void execute(int num) { for (int i = 0; i < num; i++) { lights.get[i].on(); } } @Override public void undo() { for (int i = 0; i < num; i++) { lights.get[i].off(); } } }
public class LightReceiver { public void on() { System.out.println("电灯打开了..."); } public void off() { System.out.println("电灯关闭了..."); } }
public class RemoteController { Command lightOnCommand; // 构造函数中,给这个发布命令者赋权(拥有开关灯的权利) public RemoteController(LightOnCommand command) { lightOnCommand = command; } // 命令开几盏灯 public void lightOn(int num) { lightOnCommand.execute(num); } }