Template Method模式
应用场景
当我们要完成在某一细节层次一致的一个过程或一系列步骤,但其个别步骤在更详细的层次上的实现可能不同的时候,我们通常要考虑用模板方法模式解决。
本质
优点
缺点
算法骨架不容易升级(模板和子类是非常耦合的,如要对模板中的算法骨架进行变更,会影响子类变化)
角色
AbstractClass: 定义多个抽象方法、一个模板方法ConcreteClass: 具体实现AbstractClass的抽象方法,会被AbstractClass的模板方法所调用
Template Method模式的类图
示例程序
示例程序的类图
示例代码
package templateMethod;
public abstract class AbstractDisplay {
public abstract void open ( ) ;
public abstract void print ( ) ;
public abstract void close ( ) ;
public void display ( ) {
open ( ) ;
for ( int i= 0 ; i< 5 ; i++ ) {
print ( ) ;
}
close ( ) ;
}
}
package templateMethod;
public class CharDisplay extends AbstractDisplay {
private char ch;
public CharDisplay ( char ch) {
this . ch = ch;
}
@Override
public void open ( ) {
System. out. print ( "<<" ) ;
}
@Override
public void print ( ) {
System. out. print ( ch) ;
}
@Override
public void close ( ) {
System. out. println ( ">>" ) ;
}
}
package templateMethod;
public class StringDisplay extends AbstractDisplay {
private String str;
private int width;
public StringDisplay ( String str) {
super ( ) ;
this . str = str;
this . width = str. getBytes ( ) . length;
}
private void printLine ( ) {
System. out. print ( "+" ) ;
for ( int i = 0 ; i < width; i++ ) {
System. out. print ( "-" ) ;
}
System. out. println ( "+" ) ;
}
@Override
public void open ( ) {
printLine ( ) ;
}
@Override
public void print ( ) {
System. out. println ( "|" + str + "|" ) ;
}
@Override
public void close ( ) {
printLine ( ) ;
}
}
package templateMethod;
public class Main {
public static void main ( String[ ] args) {
AbstractDisplay d1= new CharDisplay ( 'H' ) ;
AbstractDisplay d2= new StringDisplay ( "Hello,world!" ) ;
d1. display ( ) ;
d2. display ( ) ;
}
}
拓展思路
逻辑处理通用化
在父类的模板方法中编写算法,子类仅仅需要具体化抽象方法
父类、子类一致性
使用父类变量保存子类实例,很好的满足了里氏代换原则
相关的设计模式
Factory Method模式
Factory Method模式是Template Method 模式用于生成实例的一个典型例子。
Strategy模式
在Template Method模式中,使用继承改变程序的行为 在Strategy模式中,使用委托改变程序的行为 ,Strategy模式用于替换整个算法
满足的原则