Android的View类是模板方法模式的集大成者,首先我们看draw()方法的部分代码:
public void draw(Canvas canvas) {
/*
* Draw traversal performs several drawing steps which must be executed
* in the appropriate order:
*
* 1. Draw the background
* 2. If necessary, save the canvas' layers to prepare for fading
* 3. Draw view's content
* 4. Draw children
* 5. If necessary, draw the fading edges and restore layers
* 6. Draw decorations (scrollbars for instance)
* 7. If necessary, draw the default focus highlight
*/
// Step 1, draw the background, if needed
int saveCount;
drawBackground(canvas);
// ……代码省略……
// Step 2, save the canvas' layers
// ……代码省略……
// Step 3, draw the content
onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Step 5, draw the fade effect and restore layers
// ……代码省略……
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
// Step 7, draw the default focus highlight
drawDefaultFocusHighlight(canvas);
// ……代码省略……
}
private void drawBackground(Canvas canvas) {
// ……代码省略……
}
protected void onDraw(Canvas canvas) {
}
protected void dispatchDraw(Canvas canvas) {
}
public void onDrawForeground(Canvas canvas) {
// ……代码省略……
}
以上drawBackground()方法是private的,不可以重写,但onDraw()和dispatchDraw()是被protected修饰的空实现,是典型的模板方法,在View的不同子类(TextView、ImageView等)里有不同的实现。