• 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();
        }   
    }
    
  • 相关阅读:
    第一篇代码 嗨翻C语言 21点扑克
    Windows7 sp1 64位下安装配置eclipse+jdk+CDT+minGW
    MinGW-64 安装
    Windows Live Writer配置步骤
    Css 居中
    c++ 常量成员函数
    c/c++ 引用计数
    C++ 《STL源码剖析》学习-vector
    C/C++ 有符号数和无符号数
    cocos2d 内存管理机制
  • 原文地址:https://www.cnblogs.com/cpaulyz/p/13173328.html
Copyright © 2020-2023  润新知