设计模式(命令模式)
命令模式,简单一句话概括就是:把调用的方法封装起来。既然是“命令”,那么就有发送命令者(请求对象)和执行命令者(执行对象),两者均不在乎是拥有的是什么对象,只要实现了命令接口就可以了;遵循了 针对接口编程,不针对实现编程这一原则。
Command.java
public class RemoteControlTest{ public static void main(String[] args){ SimpleRemoteControl remote = new SimpleRemoteControl(); Light livingRoomLight = new Light("living Room"); Light kitchenLight = new Light("kitchen"); GarageDoorOpen gdp = new GarageDoorOpen(""); Stereo stereo = new Stereo("Living Room"); LightOnCommand livingRoomLightOn = new LightOnCommand(livingRoomLight); LightOffCommand livingRoomLightOff = new LightOffCommand(livingRoomLight); GarageDoorOpenCommand gdpc= new GarageDoorOpenCommand(gdp); StereoOnWithCDCommand stereoOnWithCD = new StereoOnWithCDCommand(stereo); StereoOffCommand stereoOff = new StereoOffCommand(stereo); remote.setCommand(0,livingRoomLightOn,livingRoomLightOff); remote.setCommand(1,stereoOnWithCD,stereoOff); System.out.println(remote); remote.onButtonWasPressed(0); remote.offButtonWasPressed(0); remote.onButtonWasPressed(1); remote.offButtonWasPressed(1); }}