命令模式对简单的调用关系进行解耦,再大多数情况下我们可以使用直接调用的方式来做,但是如果调用比较繁琐,那么使用命令模式不失为一个好选择
这里举一个超级马里奥移动的例子来讲解命令模式
超级马里奥的动作类
public class Mario {
public void toLeft() {
System.out.println("向左移");
}
public void toRight() {
System.out.println("向右移");
}
public void toJump() {
System.out.println("跳跃");
}
}
定义执行方法接口
public interface Command {
void execute();
}
定义具体命令类
- 跳命令
public class JumpCommand implements Command {
private Mario mario;
public JumpCommand(Mario mario) {
this.mario = mario;
}
@Override
public void execute() {
mario.toJump();
}
}
- 左移命令
public class LeftCommand implements Command {
private Mario mario;
public LeftCommand(Mario mario) {
this.mario = mario;
}
@Override
public void execute() {
mario.toLeft();
}
}
- 右移命令
public class RightCommand implements Command {
private Mario mario;
public RightCommand(Mario mario) {
this.mario = mario;
}
@Override
public void execute() {
mario.toRight();
}
}
命令的包装:按钮类
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();
}
}
具体执行
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();
}
}
命令类可以在相当程度上实现调用逻辑的解耦,但是像大家看到的一样,需要多出很多的类,但是这样设计模式的原则:对修改关闭,对扩展开放,才能提到体现