ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Design Pattern:命令模式

2020-06-21 17:55:48  阅读:191  来源: 互联网

标签:slot int Pattern void 模式 Command light Design public


命令模式

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

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

  • 优点: 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();
    }   
}

标签:slot,int,Pattern,void,模式,Command,light,Design,public
来源: https://www.cnblogs.com/cpaulyz/p/13173328.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有