黑马程序员技术交流社区

标题: 模板设计 [打印本页]

作者: 磊弟哥哥    时间: 2014-9-15 10:55
标题: 模板设计
/*
需求
获取一段程序运行的时间
原理:结束时间减去开始时间

获取时间   System.currentTimeMillis();



模板方法设计模式
在定义功能时,功能一部分是确定的,有一部分不确定,而且确定部分使用了不确定部分
这时将不确定部分暴漏出去,由该类的子类完成
*/
class Demo
{
        public static void main(String []args)
        {
                SubTime_1 s=new SubTime_1();
                s.gettime();
        }
}
abstract class GetTime
{
        public final void gettime()//被final修饰不能被复写了
        {
                long start=System.currentTimeMillis();
                runcode();
                long end=System.currentTimeMillis();
                System.out.println("毫秒:"+(end-start));
        }
        /*
        该函数功能知道,函数实体不确定
        所以定义成抽象
        */
        public abstract void runcode();
}
/*
将上一个类里边功能重写
class SubTime extends GetTime
{
        public void gettime()
        {
                long start=System.currentTimeMillis();
                for(int x=0;x<4000;x++)
                {
                        System.out.print(x);
                }
                long end=System.currentTimeMillis();
                System.out.println("毫秒:"+(end-start));
        }
}
*/
/*
将函数中一段代码单独拿出来封装成一个函数,子类只复写该段内容
减少了对重复代码的书写,提高代码的复用性
*/
class SubTime_1 extends GetTime
{
        public void runcode()//只复写需要改变的内容
        {
                for(int x=0;x<4000;x++)
                {
                        System.out.print(x);
                }
        }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2