Template Method 模式使用继承,来分离通用的算法和具体的上下文。
简单的讲,我有一个冒泡排序的程序,用来对int 型数据排序,要想对double 类型的数据排序,可能又得重新编写一个排序程序。Template Method 模式则避免了这种冗余的做法,它将通用的算法过程抽象出来,形成抽象基类,然后不同的算法采用自己的继承子类实现。
冒泡排序抽象基类:
public abstract class BubbleSorter
{
public void doSort()
{
for(...)
for(...)
{
if( outOfOrder(index) )
swap(index);
}
}
protected abstract void swap(int index);
protexted abstract boolean outOfOrder(int index);
}
int 型排序子类:
public IntBubbleSorter extends BubbleSorter
{
int[] array;
public void sort(int[] theArray)
{
array = theArray;
doSort();
}
@override
protected void swap(int index)
{
...// 交换元素代码
}
@override
protexted abstract boolean outOfOrder(int index)
{
return (array[index] > array[index + 1]);
}
}
这样继承了基类中的排序通用算法,仅实现了比较元素和元素交换的部分功能。
Template Method 模式展示了面向对象编程中许多经典重用形式中的一种,通用算法放在基类中,通过集成在不同的具体上下文环境中实现该算法。
缺点:派生类不可避免同基类绑定在一起,依赖性太强。