模板方法模式(Template Method)
1. 概念
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses define certain steps of an algorithm without changing the algorithm's structure.
模板方法模式在一个方法中定义一个算法的骨架,而将一些步骤的实现延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中某些步骤的具体实现。
2. 应用场景 --比如Android AsyncTask.doInBackground()
3. 代码实践
JDK:
•java.io.InputStream, java.io.OutputStream, java.io.Reader和java.io.Writer的所有非抽象方法
•java.util.AbstractList, java.util.AbstractSet和java.util.AbstractMap的所有非抽象方法
•javax.servlet.http.HttpServlet#doXXX()
Android: (以TaskExecutor机制的Task为例)
public abstract class Task<Params ,Result> implements Runnable {
private final static String TAG = "Task";
private long mId = 0;
private Context mContext;
private Task(Context context, long id){
mContext = context;
mId = id;
}
@Override
public final void run() { //1. 算法骨架(模板方法)
Result result = null;
try {
result = doInBackground();
postComplete(result);
} catch (Exception e) {
postComplete(result);
}
}
private void postComplete(final Result result){
if(TaskExecutor.mUiHandler !=null){
TaskExecutor.mUiHandler.post(new Runnable(){
@Override
public void run() {
onComplete(result);
}
});
}
}
@WorkerThread
protected abstract Result doInBackground(Params... params); //算法步骤1:执行后台耗时,延迟由子类实现
@UiThread
protected abstract void onComplete(Result result);//算法步骤2:通知UI刷新,延迟由子类实现
}
网友评论