命令设计模式

定义:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化; 对请求排队或记录请求日志,以及支持可撤销的操作。


假设手柄上有BCX等按钮,默认的功能如下。

玩家按下按键之后,执行对应的操作。

复制代码
 public static void main(String[] args) {
        String input = args[0]; //用户按键
        if (pressed(input, "B")) {
            moveLeft();
        } else if (pressed(input, "C")) {
            moveRight();
        } else if (pressed(input, "X")) {
            jump();
        }
    }

如果,支持按键自定义行为呢?

首先想到的是,保存按键和对应的行为。用户按下的时候,来判断即可。

在命令中传入player,是因为玩家的属性不同,那么跳跃、移动的力度、方式也可能不同。

复制代码
class Player {
    public static void main(String[] args) {
        String input = args[0]; //用户按键
        
        // 将一个请求封装为一个对象command,从而使你可用不同的请求对客户进行参数化
        Map<String, command> buttonForBehiverMap= getFromDb(); // 取出用户自定义的按键行为
        if (pressed(input, "B")) {
            buttonForBehiverMap.get("B").execute(this);
        } else if (pressed(input, "C")) {
            buttonForBehiverMap.get("C").execute(this);
        } else if (pressed(input, "X")) {
            buttonForBehiverMap.get("X").execute(this);
        }
    }

    private static Map<String, command> getFromDb() {
        Map<String, command> commands = new HashMap<>();
        commands.put("B", new moveRightCommand());
        commands.put("C", new moveLeftCommand());
        commands.put("X", new jumpCommand());
        return commands;
    }

    private static boolean pressed(String input, String button) {
        return false;
    }

}
interface command {
    void execute(Object player);
}
class jumpCommand implements command {
    @Override
    public void execute(Object player) {
        player.jump();
    }
}
class moveRightCommand implements command {
    @Override
    public void execute(Object player) {
        player.moveRight();
    }
}
class moveLeftCommand implements command {
    @Override
    public void execute(Object player) {
        player.moveLeft();
    }
}

命令模式还能用来对请求排队或记录请求日志,以及支持可撤销的操作。

因为每一个命令,都会调用execute(),在这个方法里面,记录下每次调用的命令就可以了。

相关推荐
.简.简.单.单.12 小时前
Design Patterns In Modern C++ 中文版翻译 第十一章 享元模式
c++·设计模式·享元模式
BD_Marathon12 小时前
设计模式——类图
设计模式
山沐与山13 小时前
【设计模式】 Python代理模式:从入门到实战
python·设计模式·代理模式
范纹杉想快点毕业13 小时前
C语言设计模式:从基础架构到高级并发系统(完整实现版)
c语言·开发语言·设计模式
她和夏天一样热14 小时前
【实战篇】设计模式在开发中的真实应用
java·开发语言·设计模式
.简.简.单.单.14 小时前
Design Patterns In Modern C++ 中文版翻译 第十章 外观模式
c++·设计模式·外观模式
山沐与山14 小时前
【设计模式】Python状态模式:从入门到实战
python·设计模式·状态模式
BD_Marathon14 小时前
设计模式的分类
设计模式
趣知岛15 小时前
Java反射和设计模式
java·开发语言·设计模式·反射
阿拉斯攀登16 小时前
设计模式:Spring MVC 中命令模式的核心映射与设计逻辑
spring·设计模式·mvc·命令模式