命令模式:將“請求”封裝成對象,以便使用不同的請求、隊列或者日志來參數化其他對象。命令模式也支持可撤銷的操作。
命令模式類圖: 下面我們來用命令模式來實現控制燈的開關。 類圖:
RemoteLoader來下發開/關燈的命令,RemoteControl來設置要調用的接口是LightOnCommand/LightOffCommand,最后由Light對象來實現具體的命令。
Light類代碼實現:
public class Light { public void on(){ System.out.Command接口代碼實現:public interface Command { public void execute(); public void undo();}LightOnCommand類代碼實現:
public class LightOnCommand implements Command{ Light light; public LightOnCommand(Light light){ this.light = light; } @Override public void execute() { // TODO Auto-generated method stub light.on(); } @Override public void undo() { // TODO Auto-generated method stub light.off(); }}LightOffCommand類代碼實現:
public class LightOffCommand implements Command{ Light light; public LightOffCommand(Light light){ this.light = light; } @Override public void execute() { // TODO Auto-generated method stub light.off(); } @Override public void undo() { // TODO Auto-generated method stub light.on(); }}RemoteControl類代碼實現:
public class RemoteControl { Command command; public void setCommand(Command command){ this.command = command; } public void buttonWaspushed(){ command.execute(); } public void undoButtonWasPushed(){ command.undo(); }}RemoteLoader類代碼實現:
public class RemoteLoader { public static void main(String[] args){ Light light = new Light(); Command lightOnCommand = new LightOnCommand(light); Command lightOffCommand = new LightOffCommand(light); RemoteControl remoteControl = new RemoteControl(); remoteControl.setCommand(lightOnCommand); remoteControl.buttonWasPushed(); remoteControl.undoButtonWasPushed(); remoteControl.setCommand(lightOffCommand); remoteControl.buttonWasPushed(); remoteControl.undoButtonWasPushed(); }}運行結果:
turn light onturn light offturn light offturn light on
|
新聞熱點
疑難解答