HeadFirst设计模式-命令模式
命令模式,将方法调用封装起来了。
Java例子:
package f_CommandPattern._01_demo; public interface Command { public void execute(); public void undo(); } //-------------------------------------- package f_CommandPattern._01_demo; //Invoker 调用者 public class SimpleRemoteControl { private Command command; public SimpleRemoteControl() { } public void setCommand(Command command) { this.command = command; } public void buttonWasPressed() { command.execute(); } } //-------------------------------------- package f_CommandPattern._01_demo; public class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.on(); } @Override public void undo() { light.off(); } } //-------------------------------------- package f_CommandPattern._01_demo; public class LightOffCommand implements Command { private Light light; public LightOffCommand(Light light) { this.light = light; } @Override public void execute() { light.off(); } @Override public void undo() { light.on(); } } //-------------------------------------- package f_CommandPattern._01_demo; //receiver 接收者 public class Light { private String roomName; public Light() { } public Light(String roomName) { this.roomName = roomName; } public void on() { System.out.println(this.roomName + " light is on..."); } public void off() { System.out.println(this.roomName + " light is off..."); } } //-------------------------------------- package f_CommandPattern._01_demo; //宏命令,多个命令的组合 public class MacroCommand implements Command { private Command[] commands; public MacroCommand(Command[] commands) { this.commands = commands; } @Override public void execute() { for (Command cmd : commands) { cmd.execute(); } } @Override public void undo() { // TODO Auto-generated method stub } } //-------------------------------------- package f_CommandPattern._01_demo; public class NoCommand implements Command { @Override public void execute() { System.out.println("no command..."); } @Override public void undo() { } } //-------------------------------------- package f_CommandPattern._01_demo; public class TestDemo { public static void main(String[] args) { SimpleRemoteControl remote = new SimpleRemoteControl(); Light light = new Light(); GarageDoor garageDoor = new GarageDoor(); LightOnCommand lighton = new LightOnCommand(light); GarageDoorOpenCommand gdoc = new GarageDoorOpenCommand(garageDoor); remote.setCommand(lighton); remote.buttonWasPressed(); remote.setCommand(gdoc); remote.buttonWasPressed(); } } //--------------------------------------
**
常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。
昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。