命令模式(Command Pattern)

命令模式:將“請求”封裝成對象,以便使用不同的請求、隊列或者日誌來參數化其他對象。命令模式也支持可撤銷的操作


案例:用戶和多調節燈案例,並且用棧實現多撤銷



代碼:圖裏面沒有畫出棧,我在User里加了記錄命令執行的棧,然後Light裏家裏燈的幾個狀態

public interface Command {

	public void execute();
	public void undo();
}

public class Light {
	
	public static final int LOW = 0;
	public static final int MID = 1;
	public static final int HIGH = 2;
	public static final int OFF = -1;
	
	private int status;
	
	public Light() {
		status = OFF;
	}

	public void setLow() {
		System.out.println("Light is be changed to low");
		status = LOW;
	}
	
	public void setMid() {
		System.out.println("Light is be changed to mid");
		status = MID;
	}
	
	public void setHigh() {
		System.out.println("Light is be changed to high");
		status = HIGH;
	}
	
	public void turnOff() {
		System.out.println("Light is turned off");
		status = OFF;
	}
	
	public int getStatus() {
		return status;
	}
}

public class User {
	private Command[] commands;
	
	private Stack<Command> s;
	
	public User() {
		s = new Stack<Command>();
	}
	
	public void setCommand(Command[] com) {
		this.commands = com;
	}
	
	public void turnOnLow() {
		commands[0].execute();
		s.push(commands[0]);
	}
	
	public void turnOnMid() {
		commands[1].execute();
		s.push(commands[1]);
	}
	
	public void turnOnHigh() {
		commands[2].execute();
		s.push(commands[2]);
	}
	
	public void turnOff() {
		commands[3].execute();
		s.push(commands[3]);
	}
	
	public void undo() {
		if (!s.isEmpty()) {
			s.pop().undo();
		}
	}
}

public class LightHighCommand implements Command {

	private Light light;
	private int preStatus;
	
	public LightHighCommand(Light light) {
		this.light = light;
	}
	
	@Override
	public void execute() {
		preStatus = light.getStatus();
		light.setHigh();
	}

	@Override
	public void undo() {
		if (preStatus == Light.LOW) {
			light.setLow();
		} else if (preStatus == Light.MID) {
			light.setMid();
		} else if (preStatus == Light.HIGH) {
			light.setHigh();
		} else if (preStatus == Light.OFF) {
			light.turnOff();
		}
	}
}

其他幾個命令類似

public class PatternDemo {
	
	public static void main(String[] args) {
		User user = new User();
		Light light = new Light();
		LightLowCommand lowCommand = new LightLowCommand(light);
		LightMidCommand midCommand = new LightMidCommand(light);
		LightHighCommand highCommand = new LightHighCommand(light);
		LightTrunOffCommand turnOffCommand = new LightTrunOffCommand(light);
		Command[] commands = new Command[] {lowCommand, midCommand, highCommand, turnOffCommand};
		
		user.setCommand(commands);
		user.turnOnLow();
		user.turnOnMid();
		user.turnOnHigh();
		user.turnOff();
		
		user.undo();
		user.undo();
		user.undo();
		user.undo();
		user.undo();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章