模板设计模式

---------------------- android培训java培训、期待与您交流! ----------------------

/*
bxd 视频day07  11节,模板设计模式
需求:获取程序运行的时间。
*/
/*★
class GetTime
{
public void getTime()
{
long start = System.currentTimeMillis();
for(int x=0;x<1000;x++)
{
System.out.print(x);
}


long end = System.currentTimeMillis();
System.out.println("毫秒:  "+(end-start));
}
}
class TemplateDemo
{
public static void main(String[] args)
{
          GetTime gt = new GetTime();
gt.getTime();
}
}
---------------------------------------------------------------------------------
★*/
/*
封装方法,继承复写:
将要计算的程序代码封装成一个函数runCode()。
以后如果要再统计其他程序的运行时间,只需要将要运行的代码封装到runCode()方法中,并覆盖掉父类GetTime的对应方法就可以了。


可以定义runCode()方法为抽象方法,这样将GetTime类定义成abstract类。具体需要计算时间的代码交给子类去复写,获取时间这一功能交给父类去完成。

class GetTime
{
public void getTime()
{
long start = System.currentTimeMillis();
runCode();


//long end = System.currentTimeMillis();
//System.out.println("毫秒:  "+(end-start));
System.out.println("毫秒:  "+(System.currentTimeMillis()-start));//将上面两段代码合为一段。
}

public void runCode()
{
for(int x=0;x<1000;x++)
{
System.out.print(x);
}
}
}
class SubTime extends GetTime
{
public void runCode()
{
for(int x=0;x<200;x++)
{
System.out.print(x+"  , ");
}
}
}
class TemplateDemo
{
public static void main(String[] args)
{


SubTime gt = new SubTime();
gt.getTime();
}
}
---------------------------------------------------------------------------------
★*/
/*
模板方法设计模式:
这种将不确定的功能定义为抽象,让子类去复写,父类只保留最基本的功能的模式。称之为模板方法设计模式。
注意:以下代码中,待执行的方法runCode()不一定要是抽象的。getTime()也不一定要定义成final,根据具体情况而已。
*/
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();//定义为abstract,是不知道将来要运行的程序代码是什么。
}
class SubTime extends GetTime
{
public void runCode()
{
for(int x=0;x<1000;x++)
{
System.out.print(x+",  ");
}
}
}
class TemplateDemo
{
public static void main(String[] args)
{
SubTime st = new SubTime();
st.getTime();
}
}


---------------------- android培训java培训、期待与您交流! ----------------------

详情请查看:http://edu.csdn.net/heima



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值