`
TRAMP_ZZY
  • 浏览: 132013 次
社区版块
存档分类
最新评论

设计模式-命令模式

 
阅读更多
public interface Command {
	
	public void execute();

}

public class NoCommand implements Command {

	@Override
	public void execute() {

	}

}

public class Light {

	public void on() {
		System.out.println("Light was on.");
	}
	
	public void off() {
		System.out.println("Light was offf.");
	}

}

public class LightOffCommand implements Command {

	private Light light;
	
	public LightOffCommand(Light light) {
		this.light = light;
	}
	
	@Override
	public void execute() {
		this.light.off();
	}

}
public class LightOnCommand implements Command {

	private Light light;
	
	public LightOnCommand(Light light) {
		this.light = light;
	}
	
	@Override
	public void execute() {
		this.light.on();
	}

}

public class Stereo {

	public void on() {
		
	}
	
	public void off() {
		
	}
	
	public void setCd() {
		
	}
	
	public void setRadio() {
		
	}
	
	public void setVolume() {
		
	}
	
}

public class StereoOffWithCommand implements Command {

	public Stereo stereo;
	
	public StereoOffWithCommand(Stereo stereo) {
		this.stereo = stereo;
	}
	
	@Override
	public void execute() {
		this.stereo.off();
	}

}
public class StereoOnWithCDCommand implements Command {

	private Stereo stereo;
	
	public StereoOnWithCDCommand(Stereo stereo) {
		this.stereo = stereo;
	}
	
	@Override
	public void execute() {
		this.stereo.on();
		this.stereo.setCd();
		this.stereo.setVolume();
	}

}

public class RemoteControl {

	Command[] onCommands;
	Command[] offCommands;
	
	public RemoteControl() {
		this.onCommands = new Command[7];
		this.offCommands = new Command[7];
		
		Command command = new NoCommand();
		for (int i=0; i<7; i++) {
			this.onCommands[i] = command;
			this.offCommands[i] = command;
		}
		
	}
	
	public void setCommand(int slot, Command onCommand, Command offCommand) {
		this.onCommands[slot] = onCommand;
		this.offCommands[slot] = offCommand;
	}
	
	public void onButtonWasPushed(int slot) {
		this.onCommands[slot].execute();
	}
	
	public void offButtonWasPushed(int slot) {
		this.offCommands[slot].execute();
	}
	
	public String toString() {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("\n---------------Remote Control----------\n");
		
		return stringBuffer.toString();
	}
	
}

public class RemoteLoader {

	public static void main(String[] args) {

		RemoteControl control = new RemoteControl();
		
		Light light = new Light();
		LightOnCommand command = new LightOnCommand(light);
		LightOffCommand offCommand = new LightOffCommand(light);
		
		Stereo stereo = new Stereo();
		StereoOnWithCDCommand cdCommand = new StereoOnWithCDCommand(stereo);
		StereoOffWithCommand stereoOffWithCommand = new StereoOffWithCommand(stereo);
		control.setCommand(0, command, offCommand);
		control.setCommand(1, cdCommand, stereoOffWithCommand);
		
		control.onButtonWasPushed(0);
		control.offButtonWasPushed(0);
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics