Template 模式和Strategy模式所要解决的问题类似,而且通常可以互换使用。
Template模式使用继承来解决问题。
Strategy模式使用委托来解决问题。
如图1:template 模式:基类 BubbleSorter实现了通用算法sort, IntBubble Sorter和Double Sorter 子类继承了父类的算法sort,分别实现子类特有的outOforder和swap方法。
如图2:Strategy模式:新建BubbleSorter,实现sort算法,同时SortHandle定义为一个接口类,使得IntBubble Sorter和DoubleBubble Sorter子类不依赖于BubbleSorter类。
所以可以在BubbleSorter之外如QuickBubbleSorter来使用IntSortHandle。
如果BubbleSorter中Sort算法是稳定的 ,则不需要抽象出SortHandle接口,使用Strategy 模式,反之,则用Strategy模式会更加灵活和可扩展。
图1Bubble Sorter的 template 模式
图2 Bubble Sorter 的strategy 模式
图3 和图4 是两外两个template模式和strategy模式的例子
图3 template 模式
图4 Strategy 模式