Design Pattern:命令模式

命令模式

  • 将“动作的请求者”从“动作的执行者“对象中解耦

  • 将”请求“封装成对象,可以支持撤销等操作

  • 优点: 1、降低了系统耦合度。 2、新的命令可以很容易添加到系统中去。

    缺点:使用命令模式可能会导致某些系统有过多的具体命令类。

  • 需要对行为进行记录、撤销或重做、事务等处理时考虑用命令模式

image-20200620204236084

应用

需求

image-20200620204417829

设计

image-20200620204429939

部分代码

public interface Command{
	public void execute();
}
public class LightOffCommand implements Command{
	Light light;
	public LightOffCommand(Light light){
		this.light = light;
	}
	public void execute(){
		light.on();
	}
}
public class RemoteControl{
    Command[] onCommands;
    Command[] offCommands;
    public RemoteControl(){
        Command noCommand = new NoCommand(); // 空对象
        for(int i = 0 ; i < 7 ; i++){
            onCommands[i] = noCommand;
            offCommands[i] = noCommand;
        }
    }
    public void setCommand(int slot,Command onCommand,Command offCommand){
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }
    public void onButtonWasPushed(int slot){
        onCommands[slot].execute();
    }
    public void offButtonWasPushed(int slot){
        offCommands[slot].execute();
    }   
}
原文地址:https://www.cnblogs.com/cpaulyz/p/13173328.html