首页 > 其他 > 详细

Design Pattern:命令模式

时间:2020-06-21 18:28:44      阅读:56      评论:0      收藏:0      [点我收藏+]

命令模式

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

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

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

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

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

技术分享图片

应用

需求

技术分享图片

设计

技术分享图片

部分代码

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

Design Pattern:命令模式

原文:https://www.cnblogs.com/cpaulyz/p/13173328.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!