类图
举例
模拟俄罗斯方块的游戏。每个下落的方块有向左移动,向右移动,加速向下和变形。
Receiver
/**
* 每个下落的俄罗斯方块
*/
public class Tetris {
/**
* 真正处理“向左”操作的逻辑代码
*/
public void toLeft(){
System.out.println("向左");
}
/**
* 真正处理“向右”操作的逻辑代码
*/
public void toRight(){
System.out.println("向右");
}
/**
* 真正处理“快速落下”操作的逻辑代码
*/
public void fastToBottom(){
System.out.println("快速落下");
}
/**
* 真正处理“改变形状”操作的逻辑代码
*/
public void transform(){
System.out.println("改变形状");
}
}
这里的Tetris 就相当于命令模式中的Receiver.是真正的执行者。
Command
public interface Command {
/**
* 命令执行方法
*/
void execute();
}
抽象Command.
CommandConcrete 具体的命令
public class LeftCommand implements Command{
private Tetris tetris;
public LeftCommand(Tetris tetris){
this.tetris = tetris;
}
public void execute() {
tetris.toLeft();
}
}
public class RightCommand implements Command {
private Tetris tetris;
public RightCommand(Tetris tetris) {
this.tetris = tetris;
}
public void execute() {
tetris.toRight();
}
}
public class FastFallCommand implements Command {
private Tetris tetris;
public FastFallCommand(Tetris tetris) {
this.tetris = tetris;
}
public void execute() {
tetris.transform();
}
}
public class TransformCommand implements Command {
private Tetris tetris;
public TransformCommand(Tetris tetris) {
this.tetris = tetris;
}
public void execute() {
tetris.fastToBottom();
}
}
Invoker 调用者
public class Button {
private LeftCommand leftCommand;
private RightCommand rightCommand;
private FastFallCommand fallCommand;
private TransformCommand transformCommand;
public void setLeftCommand(LeftCommand leftCommand) {
this.leftCommand = leftCommand;
}
public void setRightCommand(RightCommand rightCommand) {
this.rightCommand = rightCommand;
}
public void setFallCommand(FastFallCommand fallCommand) {
this.fallCommand = fallCommand;
}
public void setTransformCommand(TransformCommand transformCommand) {
this.transformCommand = transformCommand;
}
public void toLeft(){
leftCommand.execute();
}
public void toRight(){
rightCommand.execute();
}
public void toFall(){
fallCommand.execute();
}
public void toTransform(){
transformCommand.execute();
}
}
Client
public class Client {
public static void main(String[] args) {
Tetris tetris = new Tetris();
LeftCommand leftCommand = new LeftCommand(tetris);
RightCommand rightCommand = new RightCommand(tetris);
FastFallCommand fallCommand = new FastFallCommand(tetris);
TransformCommand transformCommand = new TransformCommand(tetris);
Button button = new Button();
button.setLeftCommand(leftCommand);
button.setRightCommand(rightCommand);
button.setFallCommand(fallCommand);
button.setTransformCommand(transformCommand);
button.toFall();
button.toRight();
}
}
还不太了解这种模式的使用场景。比如我可以直接在Client里面直接new Tetris 。然后直接用tetris 来实现各种行为不是更简单暴力吗。饶了这么一圈是做啥子呢?