《Head First設計模式》筆記整理...歡迎交流...設計模式
將「請求」封裝成對象,以便使用不一樣的請求、隊列或者日誌來參數化其它對象,命令模式也支持可撤銷的操做。
![圖片上傳中...]測試
public interface Command { public void execute(); } public class LightOnCommand implement Command { Light light; public LightOnCommand(Light light) { this.light = light; } public void execute() { light.on(); //execute方法調用接收對象的on方法 } } //invoker請求者 public class SimpleRemoteControl { Command slot; public SimpleRemoteControl(); public void setCommand(Command slot) { this.slot = slot; } public void buttonWasPressed() { slot.execute(); } }
測試this
SimpleRemoteControl remote = new SimpleRemoteControl(); Light xx = new Light(); LightOnCommand lightOn = new LightOnCommand(buttonWasPressed); remote.setCommand(lightOn); remote.buttonWasPressed();