Java设计模式之12——命令模式(2)

我们通过一个游戏的业务逻辑来演示命令模式。

 

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();
    }
}
 


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值