模板方法
2017-10-15 本文已影响16人
刘尔泽
详解
概念
模板方法 是通过定义一个算法骨架,而将算法中的步骤延迟到子类,这样子类就可以复写这些步骤的实现来实现特定的算法。
Activity
AsyncTask
定义抽象方法
迫使子类必须实现
使用场景
- 多个子类有共有的方法,并且逻辑基本相同时
- 重要,复杂 的算法,可以把核心算法设计为模板方法
- 重构时, 模板方法模式 是 一个经常是使用的模式
模板 还分抽象模板和具体模板
模板方法 在 Android 中的实际应用
1.activity/ fragment
2.AsynTask
只有doInBackground 是在 子线程
有返回值的runnable 是 callable
mworker = new WorkerRunnale
mFuture =new FutureTask
Future<V>
用来获取异步计算结果的,说白了就是对剧吐Runnable 或者Callable 对象任务执行的结果进行获取(get()),取消(cancle()),判断是否完成等操作
FutureTask :FutureTask 除了实现Future接口外,还实现了Runnable 接口,因此FutureTask 可以直接提交给Executor 执行。
首先看
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
然后
@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;
}
再看
public AsyncTask() {
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
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);
}
}
};
}
执行完结果后
是
postResult(result);
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
可以看到是 用handler 发送的message
然后我们查这个 消息类型 MESSAGE_POST_RESULT
找到
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;
}
}
可以看到 走了个 task 的 finish,点过去看看,
看到了 AsynTaskResult 这个类
发现 他还是个task,找finish 方法
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
可以看到如果没有结束的话做 onPostExecute 走到我们要去实现的这犯法。