ITeye博客

设计模式之命令模式

hwaspf · 2009-09-28 12:06 · 学习笔记 · Markdown

命令模式将“请求”封装成对象,实现请求调用者和请求接收者之间的解耦。

public class Light {
	String location = "";

	public Light(String location) {
		this.location = location;
	}

	public void on() {
		System.out.println(location + " light is on");
	}

	public void off() {
		System.out.println(location + " light is off");
	}
}
public interface Command {
	public void execute();
}

public class LightOnCommand implements Command {
	Light light;
 
	public LightOnCommand(Light light) {
		this.light = light;
	}
 
	public void execute() {
		light.on();
	}
 
	public void undo() {
		light.off();
	}
}
public class LightOffCommand implements Command {
	Light light;
 
	public LightOffCommand(Light light) {
		this.light = light;
	}
 
	public void execute() {
		light.off();
	}
 
	public void undo() {
		light.on();
	}
}
public class SimpleRemoteControl {
	Command slot;
 
	public SimpleRemoteControl() {}
 
	public void setCommand(Command command) {
		slot = command;
	}
 
	public void buttonWasPressed() {
		slot.execute();
	}
         
    public void undoButtonWasPushed(){
        slot.undo();
    }
      
}

public class RemoteControlTest {
	public static void main(String[] args) {
		SimpleRemoteControl remote = new SimpleRemoteControl();
		Light light = new Light("Living room");
		LightOnCommand lightOn = new LightOnCommand(light);
        LightOffCommand lightOff = new LightOffCommand(light);
		 
		remote.setCommand(lightOn);
		remote.buttonWasPressed();
        remote.undoButtonWasPushed();
		remote.setCommand(garageOpen);
		remote.buttonWasPressed();
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。