标签:系统 button 包括 void 撤销 ext 针对 执行 编程
public interface Command { void execute(); void undo(); }
public class Light { private String name; public Light(String name) { this.name = name; } public void on(){ System.out.println("开灯"); } public void off(){ System.out.println("关灯"); } }
public class LightCommand implements Command { private Light light; public LightCommand(Light light){ this.light = light; } @Override public void execute(){ light.on(); } @Override public void undo(){ light.off(); } }
public class NoCommand implements Command { public NoCommand(){ } @Override public void execute(){ System.out.println("没有打开命令"); } @Override public void undo(){ System.out.println("没有关闭命令"); } }
public class RemoteControl { Command[] commands; public RemoteControl() { commands = new Command[10]; for(int i=0;i<10;i++) { commands[i] = new NoCommand(); } } public void setCommands(int slot,Command onCommand) { commands[slot] = onCommand; } public void onButton(int slot) { commands[slot].execute(); } public void offButton(int slot) { commands[slot].undo(); } }
public class Test { public static void main(String[] args) { Light light = new Light("电灯"); LightCommand lightCommand = new LightCommand(light); RemoteControl control = new RemoteControl(); control.setCommands(0,lightCommand); control.onButton(0); control.offButton(0); control.onButton(1); control.offButton(1); } } 执行结果: 开灯 关灯 没有打开命令 没有关闭命令
标签:系统 button 包括 void 撤销 ext 针对 执行 编程
原文地址:https://www.cnblogs.com/use-D/p/9749093.html