命令模式(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();
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值