編輯:關於 Android 開發
命令模式屬於行為型模式。整體觀念並不難懂,唯一的小困擾是寫起來有點繁瑣——它把原本單純的呼叫關係拆成好幾個角色,增加了類別數量與複雜度,但換來的是依然清晰的結構。
將一個請求封裝成物件,讓使用者得以用不同的請求把客戶端參數化;同時支援請求排隊、記錄請求日誌,以及可撤銷的操作。
(1)需要把待執行的動作抽出來,以參數形式傳遞。
(2)需要在不同時刻指定、排列與執行請求;命令物件的生命週期可以與原始請求無關。
(3)需要支援操作取消。
(4)需要支援修改日誌,讓系統崩潰後這些修改能被重做一次。
(5)需要支援事務操作。
以推箱子遊戲為例。遊戲裡通常有五個按鈕:左移、右移、下移、上移、撤銷。玩家就是客戶端,五個按鈕是呼叫者,真正執行按鈕背後動作的類別則是命令角色。
接收者角色:推箱子遊戲
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 的內部操作即可,客戶端不必知道實作細節。
要不要用設計模式,取決於當前場景的複雜度與未來的擴充、維護需求。什麼都套設計模式並不恰當,這需要設計者自己權衡。
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 就是一個抽象命令者,而三個子類則是具體命令。
優點:封裝性佳、耦合更低、控制更靈活、擴充性更好。
缺點:容易導致類別膨脹,需要建立大量衍生類。
Android 學習指南(二):Android 架構與專案目錄結構解析
Android 架構概覽 Android 系統通常分為四層:Linux 核心、中介層與執行環境、應用程式架構,以及應用程式本身。每一層都封裝底層實作,並向上提供介面。
Android JNI 入門(二):C 語言資料型別、輸入輸出與記憶體操作
Android JNI 入門(二):C 語言資料型別、輸入輸出與記憶體操作 把 Hello World 寫完之後,就可以正式跨進 C 語言的門檻了。今天先談最基本的資料
msm8909 Android 5.1.1 開啟調試串口設定指南
msm8909 平台開啟 UART 調試輸出本文整理 msm8909 平台在 Android 5.1.1 下開啟調試串口輸出的關鍵設定,適用於 V1.0 與 V1.1 主
方形進度條範例 App 拆解:側滑選單、自定義 View 與彈出視窗的組合技
這個範例以開源的 android-square-progressbar 為核心,示範如何把一個方形進度條做成可以「玩」的展示頁:左側抽屜選單列出可調參數,右側畫面即時反