动态地将责任附加到对象上。想要扩展功能,装饰者提供有别于继承的另一种选择。
命令模式类图
场景解读
将开灯/关灯封装成类
利于扩展
代码展示
代码,从github下载
测试类
@Test
public void remoteControl1(){
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light();
LightOnCommand lightOn = new LightOnCommand(light);
remote.setCommand(lightOn);
remote.buttonWasPressed();
LightOffCommand lightOff = new LightOffCommand(light);
remote.setCommand(lightOff);
remote.buttonWasPressed();
}
输出结果
开灯了
关灯了
@Test
public void remoteControl2(){
RemoteControl remoteControl = new RemoteControl();
Light light = new Light();
LightOnCommand lightOnCommand = new LightOnCommand(light);
LightOffCommand lightOffCommand = new LightOffCommand(light);
remoteControl.setCommand(0,lightOnCommand,lightOffCommand);
remoteControl.onButtonWasPushed(0);
remoteControl.undoButtonWasPushed();
remoteControl.offButtonWasPushed(0);
remoteControl.undoButtonWasPushed();
}
输出结果
开灯了
关灯了
关灯了
开灯了
总结:
代码github连接
https://github.com/sky5cai/DesignModeTest