Java学习笔记(九)面向对象---模板方法设计模式

理解

在定义功能时功能的一部分是确定的,但是有一部分是不确定的,而确定的部分在使用不确定的部分,那么就将不确定的部分暴露出去,由该类的子类完成。

举例

需求

获取一段程序的运行时间

代码

abstract class GetTimeTemplate {
    public final void getTime() { //使用final修饰,防止被复写
        long start = System.currentTimeMillis();
        runCode();                //将代码以函数的形式封装
        long end = System.currentTimeMillis();
        System.out.println("时间:"+(end-start)+"毫秒");
    }
    public abstract void runCode();//代码不确定,使用abstract修饰
}
class GetTime extends GetTimeTemplate {
    /*
    此处需要运行的代码确定,继承父类后复写runCode()函数
    */
    @Override                   
    public void runCode() {
        for(int i=0; i<10000; i++)
            System.out.print(i);
    }
}
public class TemplateDemo {
    public static void main(String[] args) {
        GetTime g = new GetTime();
        g.getTime();
    }
}

猜你喜欢

转载自www.cnblogs.com/liyuxin2/p/12307753.html