设计模式——模板模式(Template)

模板模式是类的行为模式。

1.定义:

      定义一个操作中算法的骨架(或称为顶级逻辑),将一些步骤(或称为基本方法)的执行延迟到其子类中。

2.模板模式与继承

      模板方法恰当地使用了继承。此模式可以用来改写一些拥有相同功能的相关的类,将可复用的一般性行为代码移到基类里面,而把特殊化的行为代码移到子类里面。

3.模板模式中的方法

      1)模板方法:

      必须由抽象类实现,该方法是一个顶级逻辑,调用任意多个基本方法,子类不应该修改该方法。

      2)基本方法:

      模板方法所调用的方法,有可细分为抽象方法,具体方法,钩子方法

        抽象方法:强迫子类重写的

        具体方法:不需要子类重写的,最好声明为final

        钩子方法:子类可以重写的,一般是个空方法(钩子方法的命名应该以do开头,这是一个通用规范)

        补充:模板模式的设计理念是尽量减少必须由子类置换掉的基本方法的数量(可以理解为尽量减少抽象方法和钩子方法的数量。)

4.重构的原则

        总的原则:行为上移,状态下移(抽象类中的具体方法应该尽量多,而成员变量应该尽量少)

  • 应当根据行为而不是状态定义一个类
  • 在实现行为时,应该尽量用取值方法获取成员变量,而不是直接应用成员变量
  • 给操作划分层次。一个类的行为应当放到一个小组核心方法里面,这些方法可以很方便地在子类中置换
  • 将状态的确认推迟到子类中去。

5.应用场景:

        类加载,dao实现对object的增删改查。

        适用的范围:许多应用的实现有许多公共的部分,但细节有差异。

  • 从一张数据表,生成许多统计报表。
  • severlet对象service方法中doget,dopost方法。

6.实例代码:

        Template.java

package com.template;

public abstract class Template {
	
	/**
	 * 顶级逻辑
	 */
	public final void topOperation()
	{
		beforeOperation();
		
		operation();
		
		afterOperation();
	}
	
	/**
	 * 在操作前执行的方法
	 */
	private void beforeOperation()
	{
		System.out.println("this action before the operation!");
	}
	
	/**
	 * 在操作后执行的方法
	 */
	private void afterOperation()
	{
		System.out.println("this action after the operation!");
	}
	
	/**
	 * 需要推迟到子类中去实现
	 */
	protected abstract void operation();
}

TemplateImpl1.java

package com.template;

public class TemplateImpl1 extends Template{

	@Override
	protected void operation() {
		System.out.println("this action is executed in subclass TemplateImpl1!");
	}
}

 TemplateImpl2.java

package com.template;

public class TemplateImpl2 extends Template{

	@Override
	protected void operation() {
		System.out.println("this action is executed in subclass TemplateImpl2!");
	}
}

 TemplateTest.java

package com.template;

public class TemplateTest {
	public static void main(String[] args) {
		Template t1 = new TemplateImpl1();
		t1.topOperation();
		
		Template t2 = new TemplateImpl2();
		t2.topOperation();
	}
}

 运行结果:

      this action before the operation!

      this action is executed in subclass TemplateImpl1!

      this action after the operation!

      this action before the operation!

      this action is executed in subclass TemplateImpl2!

      this action after the operation!

猜你喜欢

转载自lizhao6210-126-com.iteye.com/blog/1894529
今日推荐