zoukankan      html  css  js  c++  java
  • 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();
        }   
    }
    
  • 相关阅读:
    Hibernate连接mysql数据库的配置
    opendaynight(karaf) 和 mininet测试openflow
    电信新势力,TIP/CORD能颠覆电信设备商吗?
    minnet sample
    ONIE
    升级Mininet自带的OpenvSwitch & 编译OpenvSwitch
    mininet test
    dpctl 命令实践
    白盒交换机
    Wedge 100-32X 100GbE Data Center Switch
  • 原文地址:https://www.cnblogs.com/cpaulyz/p/13173328.html
Copyright © 2011-2022 走看看