Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

《Android 源碼設計模式解析與實戰》讀書筆記(十一):命令模式

編輯:關於 Android 程式設計

第十一章、命令模式

命令模式是行為型模式之一。概念不難,但寫起來確實繁瑣——它把原本一次簡單的呼叫拆成好幾個角色,類別數量隨之增加。即便如此,只要角色劃分清楚,整體結構依然明朗。

1. 定義

將一個請求封裝成物件,讓使用者得以用不同的請求把客戶端參數化;同時支援將請求排隊、記錄請求日誌,以及可撤銷的操作。

2. 使用場景

(1)需要把待執行的動作抽取出來,以參數形式傳遞。

(2)需要在不同時刻指定、排列與執行請求。命令物件的生命週期可以與最初的請求無關。

(3)需要支援操作取消。

(4)需要支援修改日誌,以便系統崩潰後重做這些修改。

(5)需要支援事務操作。

3. 簡單實現

以推箱子遊戲為例:畫面上有五顆按鈕——左移、右移、下移、上移、撤銷。玩家是客戶端,按鈕是請求者,真正執行動作的邏輯則交給命令角色。

接收者角色(推箱子遊戲本體):

public class PushBox {
    public void toLeft()  { System.out.println("向左"); }
    public void toRight() { System.out.println("向右"); }
    public void toDown()  { System.out.println("向下"); }
    public void toUp()    { System.out.println("向上"); }
    public void revoke()  { System.out.println("撤銷"); }
}

抽象命令:

public interface Command {
    /** 執行命令 */
    void execute();
    /** 取得命令類型描述 */
    void getCommand();
}

四個移動命令與一個撤銷命令,結構一致,各自持有 PushBox 的引用:

public class LeftCommand implements Command {
    private PushBox pushBox;

    public LeftCommand(PushBox pushBox) {
        this.pushBox = pushBox;
    }

    @Override
    public void execute() {
        pushBox.toLeft();
    }

    @Override
    public void getCommand() {
        System.out.print("向左-->");
    }
}
public class RightCommand implements Command {
    private PushBox pushBox;

    public RightCommand(PushBox pushBox) {
        this.pushBox = pushBox;
    }

    @Override
    public void execute() {
        pushBox.toRight();
    }

    @Override
    public void getCommand() {
        System.out.print("向右-->");
    }
}
public class UpCommand implements Command {
    private PushBox pushBox;

    public UpCommand(PushBox pushBox) {
        this.pushBox = pushBox;
    }

    @Override
    public void execute() {
        pushBox.toUp();
    }

    @Override
    public void getCommand() {
        System.out.print("向上-->");
    }
}
public class DownCommand implements Command {
    private PushBox pushBox;

    public DownCommand(PushBox pushBox) {
        this.pushBox = pushBox;
    }

    @Override
    public void execute() {
        pushBox.toDown();
    }

    @Override
    public void getCommand() {
        System.out.print("向下-->");
    }
}
public class RevokeCommand implements Command {
    private PushBox pushBox;

    public RevokeCommand(PushBox pushBox) {
        this.pushBox = pushBox;
    }

    @Override
    public void execute() {
        pushBox.revoke();
    }

    @Override
    public void getCommand() {
    }
}

請求者類別(命令由按鈕發起,並用一個清單記錄操作歷史):

public class Buttons {

    private LeftCommand leftCommand;
    private RightCommand rightCommand;
    private UpCommand upCommand;
    private DownCommand downCommand;
    private RevokeCommand revokeCommand;

    /** 用於記錄命令動作,支援撤銷與回放 */
    private ArrayList<Command> commandList = new ArrayList<>();

    public void getCommandList() {
        for (Command c : commandList) {
            c.getCommand();
        }
        System.out.println("");
    }

    public void setLeftCommand(LeftCommand leftCommand)     { this.leftCommand = leftCommand; }
    public void setRightCommand(RightCommand rightCommand)  { this.rightCommand = rightCommand; }
    public void setUpCommand(UpCommand upCommand)           { this.upCommand = upCommand; }
    public void setDownCommand(DownCommand downCommand)     { this.downCommand = downCommand; }
    public void setRevokeCommand(RevokeCommand revokeCommand) { this.revokeCommand = revokeCommand; }

    public void toLeft() {
        leftCommand.execute();
        commandList.add(leftCommand);
    }

    public void toRight() {
        rightCommand.execute();
        commandList.add(rightCommand);
    }

    public void toUp() {
        upCommand.execute();
        commandList.add(upCommand);
    }

    public void toDown() {
        downCommand.execute();
        commandList.add(downCommand);
    }

    public void toRevoke() {
        revokeCommand.execute();
        commandList.remove(commandList.size() - 1);
    }
}

客戶端呼叫:

public class Client {
    public static void main(String[] args) {
        // 建立遊戲本體
        PushBox pushBox = new PushBox();

        // 依遊戲構造五種命令
        LeftCommand leftCommand     = new LeftCommand(pushBox);
        RightCommand rightCommand   = new RightCommand(pushBox);
        UpCommand upCommand         = new UpCommand(pushBox);
        DownCommand downCommand     = new DownCommand(pushBox);
        RevokeCommand revokeCommand = new RevokeCommand(pushBox);

        // 按鈕綁定各命令
        Buttons buttons = new Buttons();
        buttons.setLeftCommand(leftCommand);
        buttons.setRightCommand(rightCommand);
        buttons.setUpCommand(upCommand);
        buttons.setDownCommand(downCommand);
        buttons.setRevokeCommand(revokeCommand);

        buttons.toLeft();
        buttons.toDown();
        buttons.toDown();
        buttons.toRight();
        buttons.getCommandList();

        buttons.toRevoke();
        buttons.toUp();
        buttons.toLeft();
        buttons.toDown();
        buttons.toUp();
        buttons.getCommandList();
    }
}

執行結果:

向左
向下
向下
向右
向左-->向下-->向下-->向右-->
撤銷
向上
向左
向下
向上
向左-->向下-->向下-->向上-->向左-->向下-->向上-->

那這一切值得嗎?

寫完這麼長一串,難免會想:同樣的功能,三行就搞定了。

public class Client {
    public static void main(String[] args) {
        PushBox pushBox = new PushBox();
        pushBox.toDown();
        pushBox.toRight();
        pushBox.toUp();
    }
}

差別在於設計模式的核心原則:對修改關閉,對擴展開放。若採取簡化寫法,之後任何變動都得去改 PushBox 與 Client;而用命令模式,Client 完全不需要知道內部實作,擴充新命令時只要新增一個 Command 實作類別即可。

當然,模式不是越多越好。要不要用命令模式,取決於當前場景的複雜度,以及未來擴充與維護的預期。過度設計本身就是另一種問題,這需要設計者自己權衡。

4. Android 源碼中的命令模式:PackageHandler

在 PackageManagerService 中,與套件相關的訊息由其內部類 PackageHandler 承擔。需要處理的請求被當作物件透過訊息傳遞;而套件的安裝、移動與大小測量,則分別封裝為 HandlerParams 的三個子類:InstallParams、MoveParams 與 MeasureParams。

private abstract class HandlerParams {

    private static final int MAX_RETRIES = 4;

    /** startCopy() 已嘗試且遇到非致命錯誤的次數 */
    private int mRetries = 0;

    final boolean startCopy() {
        boolean res;
        try {
            if (DEBUG_INSTALL) Slog.i(TAG, "startCopy");
            if (++mRetries > MAX_RETRIES) {
                Slog.w(TAG, "Failed to invoke remote methods on default "
                        + "container service. Giving up");
                mHandler.sendEmptyMessage(MCS_GIVE_UP);
                handleServiceError();
                return false;
            } else {
                handleStartCopy();
                res = true;
            }
        } catch (RemoteException e) {
            if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
            mHandler.sendEmptyMessage(MCS_RECONNECT);
            res = false;
        }
        handleReturnCode();
        return res;
    }

    final void serviceError() {
        if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
        handleServiceError();
        handleReturnCode();
    }

    abstract void handleStartCopy() throws RemoteException;
    abstract void handleServiceError();
    abstract void handleReturnCode();
}

HandlerParams 就是一個典型的抽象命令:它定義了統一的執行骨架(startCopy() 負責重試與錯誤處理),把差異部分留給三個抽象方法,由子類各自實作。這是命令模式搭配模板方法模式的常見組合。

5. 總結

優點:封裝性良好,耦合更低,控制更靈活,擴展性更好;同時天然支援撤銷、重做與請求排隊。

缺點:類別數量膨脹,容易衍生出大量命令子類。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved