A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 磊弟哥哥 中级黑马   /  2014-9-15 10:55  /  704 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*
需求
获取一段程序运行的时间
原理:结束时间减去开始时间

获取时间   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);
                }
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马