模式命令-请说明

时间:2019-05-27 21:58:04

标签: java design-patterns

我是Java的初学者,目前我正在学习一些有关模式的知识。我了解了Factory Pattern,Sigleton等

过去一周是命令模式,但我无法理解我必须以哪种方式使用它。我已经用谷歌搜索了,但是我的大脑却炸了。

任何人都可以用简单的语言帮助我吗?

谢谢!

贡萨洛

1 个答案:

答案 0 :(得分:0)

想象一下,命令是可以抛出的对象。也许你有一个盒子。

    public class Box {
        int x;
        int y;
        ...
    }

现在,当按向左键时,您希望框向左移动一点:

    Box box = new Box(0, 0);
    if (key_pressed(K_LEFT)) {
        box.x -= 5;
    }

但是,这不遵循命令模式。相反,您可以实现一个可以像这样使用的命令:

    ArrayList<Command> commands = new ArrayList<>();
    Box box = new Box(0, 0);

    // >>> Creates all of the Commands and adds them to the queue <<< //
    if (key_pressed(K_LEFT)) {
        commands.add(new BoxMoveCommand(box, -5, 0));
    }

    // >>> Executes all the commands. <<< //
    for (Command c : commands) {
        c.execute();
    }

    commands.clear();
相关问题