模板方法设计模式

多态的应用:模板方法设计模式(TemplateMethod)
抽象类体现的就是一种模板模式的设计,抽象类作为多个子类的通用模板,子类在抽象类的基础上进行扩展、改造,但子类总体上会保留抽象类的行为方式。

解决的问题:
当功能内部一部分实现是确定的,一部分实现是不确定的,这时可以把不确定的部分暴露出去,让子类去实现。
换句话说,在软件开发中实现一个算法时,整体步骤很固定、通用,这些步骤已经在父类中写好了。但是某些部分易变,易变部分可以抽象出来,供不同子类实现,这就是一种模板模式。

模板方法设计模式是编程中经常用得到的模式。比如常见的有:

  1. 数据库访问的封装
  2. JUnit单元测试
  3. JavaWeb的Servlet中关于doGet/doPost方法调用
  4. Hibernate中模板程序
  5. Spring中JDBCTemlate、HibernateTemplate等

模板设计模式代码案例:

/*模板设计模式
 * 说明:1.相同的部分放在父类中  2.不同的部分写成抽象方法由子类去实现
 */
// 计算代码运行时间
abstract class SuperClass{
	public void runTime(){
		//1.开始时间
		long start=System.currentTimeMillis();//距离1970年1月1日  0时0分0秒的毫秒数
		//2.执行代码
		this.runCode();// 多态  对象是谁,调用的就是谁的runCode方法
		//3.结束时间
		long end = System.currentTimeMillis();
		//4.计算时间差
		System.out.println("\ntime = "+(end-start));
	}
	public abstract void runCode();
}

class Computer2 extends SuperClass{
	public void runCode(){
		System.out.println("Computer1: ");
		for(int i=0; i<10; i++){
			System.out.print(i+", ");
		}
	}
}

class Computer3 extends SuperClass{
	public void runCode(){
		System.out.println("\nComputer2: ");
		for(int i=0; i<10; i++){
			if(i%2==0){
				System.out.print(i+", ");
			}						
		}
	}
}

public class TemplateMethodTest {
	public static void main(String[] args) {
		SuperClass sc1 = new Computer1();
		sc1.runTime();
		SuperClass sc2 = new Computer2();
		sc2.runTime();
	}
}


执行结果

Computer1: 
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
time = 0

Computer2: 
0, 2, 4, 6, 8, 
time = 0
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值