1 命令
/**
* 命令 抽象类
*/
public interface Command {
public void execute();
}
2 具体命令
/**
* 具体命令
*/
public class RightCommand implements Command {
//持有一个接收者对象的引用
private TetrisMachine tetrisMachine;
public RightCommand(TetrisMachine tetrisMachine) {
this.tetrisMachine = tetrisMachine;
}
@Override
public void execute() {
tetrisMachine.toRight();
}
}
/**
* 具体命令
*/
public class LeftCommand implements Command {
//持有一个接收者对象的引用
private TetrisMachine tetrisMachine;
public LeftCommand(TetrisMachine tetrisMachine) {
this.tetrisMachine = tetrisMachine;
}
@Override
public void execute() {
tetrisMachine.toLeft();
}
}
3 机器 执行者相当于Reciever的抽象
/**
* 方便在新增加命令时 -对功能进行重写
*/
public interface ITetrisMache {
public void toTop();
public void toBottom();
public void toLeft();
public void toRight();
}
4 具体机器
/**
* 具体俄罗斯方块命令接收者-相当于Reciever
*/
public class TetrisMachine implements ITetrisMache{
public void toTop(){
Log.i("***","向上");
}
public void toBottom(){
Log.i("***","向下");
}
public void toLeft(){
Log.i("***","向左");
}
public void toRight(){
Log.i("***","向右");
}
}
5 命令发起者
/**
* 请求者类--命令由按钮引起
*/
public class Buttons {
private LeftCommand leftCommand;//向左命令引用
private RightCommand rightCommand;//向右命令引用
//设置向左命令对象
public void setLeftCommand(LeftCommand leftCommand) {
this.leftCommand = leftCommand;
}
//设置向右命令对象
public void setRightCommand(RightCommand rightCommand) {
this.rightCommand = rightCommand;
}
//按下向左移动
public void toLeft(){
leftCommand.execute();
}
//按下向右移动
public void toRight(){
rightCommand.execute();
}
}
6 玩家 命令模式/非命令模式对比
/**
* 玩家类,,,对修改关闭对扩展开放----可以增加其他的命令
* 不同的机器,不同命令组合
*/
public class Player {
public void play(){
//首先有个机器
TetrisMachine machine = new TetrisMachine();
//游戏规则 命令
LeftCommand leftCommand = new LeftCommand(machine);
RightCommand rightCommand = new RightCommand(machine);
//不同的按钮执行不同的命令
Buttons buttons = new Buttons();
buttons.setLeftCommand(leftCommand);
buttons.setRightCommand(rightCommand);
//具体按下那个按钮玩家说了算
buttons.toLeft();
buttons.toRight();
}
}
/**
* 玩家类,,,对修改关闭对扩展开放----可以增加其他的命令
* 命令模式解耦的是 接受者和调用者(这里没有解耦)
* 命令模式初衷,是功能方法的抽象,将一个功能方法提升到对象来操作。
*/
public class ErrorPlayer {
public void play(){
//俄罗斯方块机器
TetrisMachine machine = new TetrisMachine();
//实现怎样的方式,直接调用函数
machine.toLeft();
machine.toRight();
machine.toTop();
machine.toBottom();
}
}