Android原始碼設計模式之模板方法模式
在面向物件開發中,通常會遇到這樣一個問題,我們知道一個演算法所需的關鍵步驟,並確定了這些步驟的執行順序,但是某些步驟的具體實現是未知的,或者說某些步驟的實現是會隨著環境的變化而改變的,例如,執行程式的流程大致如下:
1.檢查程式碼的正確性;
2.連結相關的類庫;
3.編譯相關的程式碼;
4.執行程式;
對於不同的程式設計語言,上述4個步驟是不一樣的,但是,它們的執行流程是固定的,這類問題的解決方案就是模板方法模式。
模板方法模式的定義
定義一個操作中的演算法的框架,而將這一些步驟延遲到子類中,使得子類可以不改變一個演算法的結構即可重新定義該演算法的某些步驟。
模板方法模式的使用場景
1.多個子類有公有的方法,並且邏輯基本相同時。
2.重要、複雜的演算法,可以把核心演算法設計為模板方法,周邊的相關細節功能則由各個子類去實現。
3.重構時,模板方法模式是一個經常使用的模式,把相同的程式碼抽取到父類中,然後通過鉤子函式約束其行為。
模板方法模式的UML圖
模板方法實際上是封裝了一個固定流程,就像是一套執行模板一樣,第一步該做什麼,第二步該做什麼都已經在抽象類中定義好了。而子類可以有不同的演算法實現,在框架不被修改的情況下實現某些步驟的演算法替換。
模板設計模式簡單Demo
package templete.gome.com.templetedemo; import android.util.Log; /** * Created by ying.zhang on 2018/8/7. * 抽象Computer */ public abstract class AbstractComputer { protected static final String TAG = "zy"; protected void powerOn() { Log.v(TAG, "開啟電源"); } protected void checkHardware() { Log.v(TAG, "硬體檢查"); } protected void loadOS() { Log.v(TAG, "載入作業系統"); } protected void login() { Log.v(TAG, "計算機無驗證,直接進入系統"); } /** * 啟動計算機方法、步驟固定為開啟電源、系統檢查、載入作業系統、使用者登入 * 方法為final,防止演算法框架被覆寫 */ public final void startUp() { Log.v(TAG, "-----------開機 START--------------"); powerOn(); checkHardware(); loadOS(); login(); Log.v(TAG, "------------關機 END--------------"); } }
package templete.gome.com.templetedemo;
import android.util.Log;
/**
* Created by ying.zhang on 2018/8/7.
*/
public class CoderComputer extends AbstractComputer {
@Override
protected void login() {
Log.v(TAG, "程式設計師只需要進行使用者和密碼登入驗證就可以了");
}
}
package templete.gome.com.templetedemo; import android.util.Log; /** * Created by ying.zhang on 2018/8/7. */ public class MilitaryComputer extends AbstractComputer { @Override protected void checkHardware() { super.checkHardware(); Log.v(TAG, "檢查硬體防火牆"); } @Override protected void login() { Log.v(TAG,"進行指紋識別等複雜的使用者驗證"); } }
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AbstractComputer comp = new CoderComputer();
comp.startUp();
comp = new MilitaryComputer();
comp.startUp();
}
}
Log分析:
V/zy: -----------開機 START--------------
V/zy: 開啟電源
V/zy: 硬體檢查
V/zy: 載入作業系統
V/zy: 程式設計師只需要進行使用者和密碼登入驗證就可以了
V/zy: ------------關機 END--------------
V/zy: -----------開機 START--------------
V/zy: 開啟電源
V/zy: 硬體檢查
V/zy: 檢查硬體防火牆
V/zy: 載入作業系統
V/zy: 進行指紋識別等複雜的使用者驗證
V/zy: ------------關機 END--------------
Android原始碼中的模板方法模式
在Android中,AsyncTask是比較常用的一種型別,這個類就使用了模板方法模式。這裡只分析在該類中使用的模板方法模式。
在使用AsyncTask時,我們都知道把耗時方法放在doInBackground(Params... params) 中,在doInBackgroud之前,如果還想做一些類似初始化的操作,可以把方法寫在onPreExecute 中,當doInBackground 執行完畢後,則會執行 onPostExecute 方法,而我們只需要構建AsyncTask物件,然後執行execute方法即可。
它的整個執行過程其實是一個框架,具體的是實現都需要在子類中完成,而且它執行的演算法框架是固定,呼叫execute後會依次執行onPreExecute 、doInBackground 、doInBackground 方法,當然也可以通過onProgressUpdate 來更新進度。
public abstract class AsyncTask<Params, Progress, Result> {
}
#AsyncTask(Android 8.1)
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
#AsyncTask(Android 8.1)
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
#AsyncTask(Android 8.1)
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
#AsyncTask(Android 8.1)
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR;
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
#AsyncTask(Android 8.1)
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
// We want at least 2 threads and at most 4 threads in the core pool,
// preferring to have 1 less than the CPU count to avoid saturating(飽和)
// the CPU with background work
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE_SECONDS = 30;
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
#AsyncTask(Android 8.1)
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
/**
* Indicates the current status of the task. Each status will be set only once
* during the lifetime of a task.
*/
public enum Status {
/**
* Indicates that the task has not been executed yet.
*/
PENDING,
/**
* Indicates that the task is running.
*/
RUNNING,
/**
* Indicates that {@link AsyncTask#onPostExecute} has finished.
*/
FINISHED,
}
execute方法是一個final方法,它呼叫了executeOnExecutor方法,在該方法中會判斷該任務的狀態,如果不是PENDING狀態則丟擲異常,這也解釋了為什麼AsyncTask只能被執行一次,因為AsyncTask的RUNNING和FINISHED狀態都會丟擲異常,因此,每次使用AsyncTask時都需要重新建立一個物件。
因為在executeOnExecutor方法中首先執行了onPreExecute()方法,因為AsyncTask的要求是需要在UI執行緒呼叫execute方法,因此,onPreExecute方法也執行在UI執行緒,然後將params引數傳遞給mWorker物件的mParams欄位,並且執行了exec.execute(mFuture)方法。
public abstract class AsyncTask<Params, Progress, Result> {
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
}
mWorker和mFuture又是什麼呢?其實mWorker只是實現了Callable介面,並添加了一個引數陣列欄位。
#AsyncTask(Android 8.1)
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();(執行緒安全)
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
//構建一個Worker物件
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
//呼叫doInBackground方法,並且將結果傳遞出去。
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
//將結果傳遞出去
postResult(result);
}
return result;
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
#AsyncTask(Android 8.1)
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
#AsyncTask(Android 8.1)
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
D:\AndroidSdk\sources\android-26\java\util\concurrent\Callable.java
JDK中的Callable
package java.util.concurrent;
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
#AsyncTask(Android 8.1)
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));//這邊傳入的this就是一個AsyncTask例項
message.sendToTarget();
return result;
}
簡單地說就是mFuture包裝了這個mWorker物件,在這個mFuture物件的run函式中又會呼叫mWorker物件的call方法,在call方法中又呼叫了doInBackgroud函式。因為mFuture提交給了執行緒池來執行,所以,使得doInBackgroud執行在非UI執行緒。得到doInBackgroud的結果後,最後通過postResult傳遞結果給UI執行緒,我們再看看postResult的實現。
#AsyncTask(Android 8.1)
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
private Handler getHandler() {
return mHandler;
}
//實際執行的是 getMainHandler()。
private static Handler getMainHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler(Looper.getMainLooper());
}
return sHandler;
}
}
private static class InternalHandler extends Handler {
public InternalHandler(Looper looper) {
super(looper);
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
//呼叫AsyncTask的finish方法
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
D:\AndroidSdk\sources\android-26\java\util\concurrent\FutureTask.java
public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
D:\AndroidSdk\sources\android-26\java\util\concurrent\FutureTask.java
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
從程式中可以看到,postResult就是把一個訊息(msg.what == MESSAGE_POST_RESULT)傳送給sHandler,sHandler為InternalHandler型別,當InternalHandler接收到MESSAGE_POST_RESULT型別的訊息時就會呼叫 result.mTask.finish(result.mData[0]);方法。我們看到result為AsyncTaskResult型別。
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
從上述程式可以看到mTask就是AsyncTask物件,呼叫AsyncTask物件的finish方法時又呼叫onPostExecute方法,整個執行過程就完成了。
總之,execute方法內部封裝了onPreExecute、doInBackgroud、onPostExecute這個邏輯流程,使用者可以根據需求再覆寫這幾個方法,使得使用者可以很方便地使用非同步任務來完成耗時操作以及更新UI,這其實是通過執行緒池來完成耗時任務,得到結果之後,通過Handler將結果傳遞給UI執行緒來執行。
參考《Android原始碼設計模式》