命令模式

命令模式UML.png
class GameBoy{
public void toLeft(){
//左移
}
public void toRight(){
//右移
}
public void toTop(){
//上移
}
public void toBottom(){
//下移
}
public void toA(){
//A鍵出拳
}
public void toB(){
//B鍵踢腿
}
}
GameBoy,游戲機類
interface Command{
void execute();
}
按鈕接口
class LeftCommand implements Command{
private GameBoy gameBoy;
public LeftCommand(GameBoy gameBoy){
this.gameBoy = gameBoy;
}
public void execute(){
gameBoy.toLeft();
}
}
class RightCommand implements Command{
private GameBoy gameBoy;
public RightCommand(GameBoy gameBoy){
this.gameBoy = gameBoy;
}
public void execute(){
gameBoy.toRight();
}
}
class TopCommand implements Command{
private GameBoy gameBoy;
public TopCommand(GameBoy gameBoy){
this.gameBoy = gameBoy;
}
public void execute(){
gameBoy.toTop();
}
}
class BottomCommand implements Command{
private GameBoy gameBoy;
public BottomCommand(GameBoy gameBoy){
this.gameBoy = gameBoy;
}
public void execute(){
gameBoy.toBottom();
}
}
class ACommand implements Command{
private GameBoy gameBoy;
public ACommand(GameBoy gameBoy){
this.gameBoy = gameBoy;
}
public void execute(){
gameBoy.toA();
}
}
class BCommand implements Command{
private GameBoy gameBoy;
public BCommand(GameBoy gameBoy){
this.gameBoy = gameBoy;
}
public void execute(){
gameBoy.toB();
}
}
上述六個類是具體的按鍵 上下左右AB鍵
class Buttons{
private Command leftCommand,rightCommand,topCommand,bottomCommand,aCommand,bCommand;
public Buttons(Command leftCommand, Command rightCommand, Command topCommand, Command bottomCommand, Command aCommand, Command bCommand){
this.leftCommand = leftCommand;
this.rightCommand = rightCommand;
this.topCommand = topCommand;
this.bottomCommand = bottomCommand;
this.aCommand = aCommand;
this.bCommand = bCommand;
}
public void toLeft(){
leftCommand.execute();
//左移
}
public void toRight(){
rightCommand.execute();
//右移
}
public void toTop(){
topCommand.execute();
//上移
}
public void toBottom(){
bottomCommand.execute();
//下移
}
public void toA(){
ACommand.execute();
//A鍵出拳
}
public void toB(){
BCommand.execute();
//B鍵踢腿
}
}
鍵盤按鈕類,開關(guān)類
public class Client{
public static void main(String[] args){
GameBoy gameBoy = new GameBoy();//游戲機先創(chuàng)建出來
// 上下左右AB命令
Command leftCommand,rightCommand,topCommand,bottomCommand,aCommand,bCommand;
leftCommand = new LeftCommand(gameBoy);
rightCommand = new RightCommand(gameBoy);
topCommand = new TopCommand(gameBoy);
bottomCommand = new BottomCommand(gameBoy);
aCommand = new ACommand(gameBoy);
bCommand = new BCommand(gameBoy);
// 具體操作的按鍵
Buttons buttons = new Buttons(leftCommand,rightCommand,topCommand,bottomCommand,aCommand,bCommand);
//按鍵按下執(zhí)行操作
buttons.toLeft();
buttons.toRight();
buttons.toTop();
buttons.toBottom();
buttons.toA();
buttons.toB();
}
}
個人總結(jié)
上述用例講的是一個小游戲機運用了命令模式,將按鈕這個動作請求和具體實現(xiàn)功能解耦。功能上的解耦伴隨的代價是類的數(shù)量的增多,在實際開發(fā)中根據(jù)場景來考量是否采用。