模板方法模式 Template Method
GOF给模板方法(Template Method)模式定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。这里的算法的结构,可以理解为你根据需求设计出来的业务流程。特定的步骤就是指那些可能在内容上存在变数的环节。
可以看出来,模板方法模式也是为了巧妙解决变化对系统带来的影响而设计的。使用模板方法使系统扩展性增强,最小化了变化对系统的影响。这一点,在下面的举例中可以很明显的看出来。
UML:
?
例子:
?
?
public class Trip { public final void performTrip(){ doComingTransport(); doDayA(); doDayB(); doDayC(); doReturningTransport } public abstract void doComingTransport(); public abstract void doDayA(); public abstract void doDayB(); public abstract void doDayC(); public abstract void doReturningTransport();}public class PackageA extends Trip { public void doComingTransport() { System.out.println("The turists are comming by air ..."); } public void doDayA() { System.out.println("The turists are visiting the aquarium ..."); } public void doDayB() { System.out.println("The turists are going to the beach ..."); } public void doDayC() { System.out.println("The turists are going to mountains ..."); } public void doReturningTransport() { System.out.println("The turists are going home by air ..."); }}public class PackageB extends Trip { public void doComingTransport() { System.out.println("The turists are comming by train ..."); } public void doDayA() { System.out.println("The turists are visiting the mountain ..."); } public void doDayB() { System.out.println("The turists are going to the beach ..."); } public void doDayC() { System.out.println("The turists are going to zoo ..."); } public void doReturningTransport() { System.out.println("The turists are going home by train ..."); }}
?