我们通过一个游戏的业务逻辑来演示命令模式。
1 创建命令接口:
package commandpattern2;
public interface Command {
void execute();
}
2 创建命令的执行者:
package commandpattern2;
/**
* 具体执行类 相当于 Receiver
*/
public class TetrisMachine {
public void toLeft(){
System.out.println("向左");
}
public void toRight(){
System.out.println("向右");
}
public void toFall(){
System.out.println("快速落下");
}
public void toTansform(){
System.out.println("改变形状");
}
}
3 封装具体的命令:
package commandpattern2;
public class LeftCommand implements Command{
private TetrisMachine mTetrisMachine;
public LeftCommand(TetrisMachine mTetrisMachine) {
this.mTetrisMachine = mTetrisMachine;
}
@Override
public void execute() {
mTetrisMachine.toLeft();
}
}
package commandpattern2;
public class RightCommand implements Command{
private TetrisMachine mTetrisMachine;
public RightCommand(TetrisMachine mTetrisMachine) {
this.mTetrisMachine = mTetrisMachine;
}
@Override
public void execute() {
mTetrisMachine.toRight();
}
}
4 发出命令的请求:
package commandpattern2;
/**
* 相当于 Invoker
*/
public class Buttons {
private Command mLeftCommand;
private Command mRightCommand;
public void setRightCommand(RightCommand command){
mRightCommand = command;
}
public void setLeftCommand(LeftCommand command){
mLeftCommand = command;
}
public void toLeft(){
mLeftCommand.execute();
}
public void toRight(){
mRightCommand.execute();
}
}
5 玩家操作游戏:
package commandpattern2;
public class Player {
public static void main(String[] args) {
//构造游戏的操作界面
TetrisMachine machine = new TetrisMachine();
//构造游戏的命令对象
RightCommand rightCommand = new RightCommand(machine);
LeftCommand leftCommand = new LeftCommand(machine);
//给按钮添加不同的命令
Buttons buttons = new Buttons();
buttons.setLeftCommand(leftCommand);
buttons.setRightCommand(rightCommand);
//玩家按下按钮 ,发出命令
buttons.toLeft();
buttons.toRight();
}
}