1.模板模式的定義及使用場(chǎng)景
定義一個(gè)操作中的算法框架,而將一些步驟延遲到子類中,使得子類可以不改變一個(gè)算法的結(jié)構(gòu)即可重定義該算法的某些特定步驟。
使用場(chǎng)景:
多個(gè)子類有公有的方法,并且邏輯基本相同
重要、復(fù)雜的算法,可以把核心算法設(shè)計(jì)為模板方法,周邊的相關(guān)細(xì)節(jié)功能則由各個(gè)子類實(shí)現(xiàn)
重構(gòu)時(shí),模板方法模式是一個(gè)經(jīng)常使用的模式,把相同的代碼抽取到父類中,然后通過鉤子函數(shù)約束其行為
2.模板模式的優(yōu)缺點(diǎn)
2.1優(yōu)點(diǎn)
封裝不變的部分,擴(kuò)展可變部分
提取公共部分代碼,便于維護(hù)
行為由父類控制,子類實(shí)現(xiàn)
2.2缺點(diǎn)
抽象類定義了部分抽象方法,由子類實(shí)現(xiàn),子類執(zhí)行的結(jié)果影響父類的結(jié)果,也就是子類對(duì)父類產(chǎn)生了影響,在負(fù)責(zé)的項(xiàng)目中,會(huì)帶來代碼閱讀的復(fù)雜性
2.3注意事項(xiàng)
在開發(fā)中經(jīng)常遇到一個(gè)問題,父類怎么調(diào)用子類的方法?應(yīng)善用模板模式,避免如下的使用:
把子類傳遞到父類的有參構(gòu)造中,然后調(diào)用
使用反射的反射調(diào)用
父類調(diào)用子類的靜態(tài)方法
3.模板模式的實(shí)現(xiàn)方式
AbstactTemple
public abstract class AbstactTemple {
protected abstract void doOne();
protected abstract boolean doTwo();
public final void templeMethod() {
doOne();
if (doTwo()) {
System.out.println("the world is bueatiful");
}
}
}```
ConcreteTempleOne
public class ConcreteTempleOne extends AbstactTemple {
@Override
protected void doOne() {
System.out.println("ConcreteTempleOne:" + "doOne");
}
@Override
protected boolean doTwo() {
return true;
}
}```
ConcreteTempleTwo
public class ConcreteTempleTwo extends AbstactTemple {
@Override
protected void doOne() {
System.out.println("ConcreteTempleTwo:" + "doOne");
}
@Override
protected boolean doTwo() {
return false;
}
}```
Test
public class Test {
public static void main(String args[]) {
AbstactTemple templeOne = new ConcreteTempleOne();
AbstactTemple templeTwo = new ConcreteTempleTwo();
templeOne.templeMethod();
templeTwo.templeMethod();
}
}```
4.模板模式在Android中的實(shí)際應(yīng)用
在Android中,AsyncTask是比較常見的一個(gè)類型,這個(gè)類就是使用了模板模式。在使用AsyncTask時(shí),我們都知道把耗時(shí)的方法放在doInBackground(Params… params)中,在doInBackground之前,如果還想做一些類似初始化的操作,可以把實(shí)現(xiàn)卸載onPreExecutre方法中,當(dāng)doInBackground方法執(zhí)行完成后,會(huì)執(zhí)行onPostExecutre方法,而我們只需要構(gòu)建AsyncTask對(duì)象,然后執(zhí)行exexute方法即可。
AsyncTask主要使用了線程池及任務(wù)隊(duì)列,handle消息機(jī)制。
啟動(dòng)執(zhí)行:將任務(wù)交由線程池處理
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
ublic 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;
}```
處理消息隊(duì)列:
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
Result result = doInBackground(mParams); //處理后臺(tái)的方法
Binder.flushPendingCommands();
return postResult(result); //消息分發(fā)
}
};
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);
}
}
};
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}```
處理Mesage消息:
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@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
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);//處理完成的回調(diào)
}
mStatus = Status.FINISHED;
}