命令设计模式

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


假设手柄上有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(),在这个方法里面,记录下每次调用的命令就可以了。

相关推荐
YHL12 小时前
🎯 JavaScript 单例模式(Singleton Pattern)—— 从理论到实战
javascript·设计模式
2401_8685347814 小时前
网络环境规划核心考点全梳理
网络·设计模式
feiyu_gao18 小时前
Cocreation Framework:一套给所有人的 AI 协作思考系统
设计模式·aigc·ai编程
善良勤劳勇敢而又聪明的老杨2 天前
【AI编程系列】MCP 常用设计模式解读
设计模式·ai编程
geovindu2 天前
java: Strategy Pattern
java·开发语言·后端·设计模式·策略模式·行为模式
码匠许师傅2 天前
【设计模式精讲】29.行为型模式总结与对比(Behavioral Patterns Summary)
c++·设计模式·uml
geovindu2 天前
CSharp: Observer Pattern
开发语言·后端·观察者模式·设计模式·c#·.netcore·行为模式
YHHLAI3 天前
NestJS 后端开发实战:从设计模式到 CRUD 全栈
设计模式
2401_868534784 天前
长远目标 Long-term Goal 老题沿用
设计模式·需求分析
吃饱了得干活4 天前
Java设计模式实战:一个支付模块的重构之旅,层层递进理解设计模式精髓
后端·设计模式·架构