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


 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章