Fork me on GitHub

命令模式

命令模式对简单的调用关系进行解耦,再大多数情况下我们可以使用直接调用的方式来做,但是如果调用比较繁琐,那么使用命令模式不失为一个好选择

这里举一个超级马里奥移动的例子来讲解命令模式

超级马里奥的动作类

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Mario {
public void toLeft() {
System.out.println("向左移");
}

public void toRight() {
System.out.println("向右移");
}

public void toJump() {
System.out.println("跳跃");
}
}

定义执行方法接口

1
2
3
public interface Command {
void execute();
}

定义具体命令类

  1. 跳命令

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class JumpCommand implements Command {
    private Mario mario;
    public JumpCommand(Mario mario) {
    this.mario = mario;
    }
    @Override
    public void execute() {
    mario.toJump();
    }
    }
  2. 左移命令

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class LeftCommand implements Command {
    private Mario mario;
    public LeftCommand(Mario mario) {
    this.mario = mario;
    }
    @Override
    public void execute() {
    mario.toLeft();
    }
    }
  3. 右移命令

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class RightCommand implements Command {
    private Mario mario;
    public RightCommand(Mario mario) {
    this.mario = mario;
    }
    @Override
    public void execute() {
    mario.toRight();
    }
    }

命令的包装:按钮类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Button {
private JumpCommand jumpCommand;
private LeftCommand leftCommand;
private RightCommand rightCommand;

public void setJumpCommand(JumpCommand jumpCommand) {
this.jumpCommand = jumpCommand;
}

public void setLeftCommand(LeftCommand leftCommand) {
this.leftCommand = leftCommand;
}

public void setRightCommand(RightCommand rightCommand) {
this.rightCommand = rightCommand;
}

public void jump() {
jumpCommand.execute();
}

public void left() {
leftCommand.execute();
}

public void right() {
rightCommand.execute();
}
}

具体执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
Mario mario = new Mario();
LeftCommand leftCommand = new LeftCommand(mario);
RightCommand rightCommand = new RightCommand(mario);
JumpCommand jumpCommand = new JumpCommand(mario);
Button button = new Button();
button.setJumpCommand(jumpCommand);
button.setLeftCommand(leftCommand);
button.setRightCommand(rightCommand);
button.jump();
button.left();
button.right();
}
}

命令类可以在相当程度上实现调用逻辑的解耦,但是像大家看到的一样,需要多出很多的类,但是这样设计模式的原则:对修改关闭,对扩展开放,才能提到体现