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

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

具體命令者(以左移為例,其餘四個結構相同)

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 Buttons {
    private LeftCommand leftCommand;     // 向左移動的命令物件
    private RightCommand rightCommand;   // 向右移動的命令物件
    private UpCommand upCommand;         // 向上移動的命令物件
    private DownCommand downCommand;     // 向下移動的命令物件
    private RevokeCommand revokeCommand; // 撤銷命令物件
    private ArrayList 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 完全不需要動,只要替換或擴充 PushBox 的內部操作即可,客戶端不必知道實作細節。

要不要用設計模式,取決於當前場景的複雜度與未來的擴充、維護需求。什麼都套設計模式並不恰當,這需要設計者自己權衡。

4. Android 原始碼中的命令模式

PackageHandler

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

private abstract class HandlerParams {
    private static final int MAX_RETRIES = 4;

    /** Number of times startCopy() has been attempted and had a non-fatal error. */
    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 就是一個抽象命令者,而三個子類則是具體命令。

5. 總結

優點:封裝性佳、耦合更低、控制更靈活、擴充性更好。

缺點:容易導致類別膨脹,需要建立大量衍生類。

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