`
hwaspf
  • 浏览: 8048 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
最近访客 更多访客>>
社区版块
存档分类
最新评论

设计模式之命令模式

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

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();
    }
}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics