命令设计模式

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


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

相关推荐
七月丶20 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞20 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼21 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟2 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder2 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室2 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦3 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo6 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4966 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃6 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式