多态的应用:模板方法设计模式(TemplateMethod)
抽象类体现的就是一种模板模式的设计,抽象类作为多个子类的通用模板,子类在抽象类的基础上进行扩展、改造,但子类总体上会保留抽象类的行为方式。
解决的问题:
当功能内部一部分实现是确定的,一部分实现是不确定的,这时可以把不确定的部分暴露出去,让子类去实现。
换句话说,在软件开发中实现一个算法时,整体步骤很固定、通用,这些步骤已经在父类中写好了。但是某些部分易变,易变部分可以抽象出来,供不同子类实现,这就是一种模板模式。
模板方法设计模式是编程中经常用得到的模式。比如常见的有:
- 数据库访问的封装
- JUnit单元测试
- JavaWeb的Servlet中关于doGet/doPost方法调用
- Hibernate中模板程序
- 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