黑马程序员技术交流社区
标题:
关于模板方法设计模式的疑问【已解决】
[打印本页]
作者:
位雪
时间:
2012-8-19 11:28
标题:
关于模板方法设计模式的疑问【已解决】
本帖最后由 位丹丹 于 2012-8-20 23:50 编辑
关于模版方法设计模式的疑问
abstract class GetTime//此类是获取某段代码运行的时间
{
public void getTime()
{
long start = System.currentTimeMillis();
/*for(int x = 0;x<1000;x++)
{
System.out.print(x);
}*/
runcode();
long end = System.currentTimeMillis();
System.out.println("毫秒:"+(end-start));
}
public abstract void runcode();
/*
* 程序运行代码未知,只是获取时间的一种方式
{
for(int x=0;x<1000;x++)
{
System.out.println(x);
}
}*/
}
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));
}*/
//子继父类,只需要复写父类功能定义自己的特有功能
public void runcode()
{
for(int x = 0;x<4000;x++)
{
System.out.print(x);
}
}
}
public class TemplateDemo {
public static void main(String[] args) {
//GetTime gt = new GetTime();
SubTime gt = new SubTime();
gt.getTime();
}
}
疑问:用这个模式能否求出视频运行时间,用代码怎么实现?求助。。。。。
复制代码
作者:
唐杨老师
时间:
2012-8-20 23:11
package my;
abstract class GetTime// 此类是获取某段代码运行的时间
{
public void getTime() {
long start = System.currentTimeMillis();
runcode();
long end = System.currentTimeMillis();
System.out.println("耗时" + (end - start) + "毫秒:");
}
public abstract void runcode();
}
class SubTime extends GetTime {
public void runcode(){};
}
public class TemplateDemo {
public static void main(String[] args) {
SubTime gt = new SubTime() {
@Override
public void runcode() {
<font color="#ff0000"> System.out.println("程序开始:");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("程序结束");</font>
}
};
gt.getTime();
}
}
复制代码
把主方法里的红色部分改成自己向运行的代码..
就可以统计了.这个使用的是内部类.重写runcode的方法.
作者:
冯培军
时间:
2012-8-20 23:26
模版方法设计模式
规定一个体系,但是其中有的一部分需要用户自己去编写,其他的按部就班,这个体系就叫做模版设计模式,例如:一个类有一个模版,执行顺序是第一、第二 、第三 ,但是不知道第二怎么去执行,把这部分抽象出来,那个这个类也是抽象类了。子类在继承这个类时,只要实现第二个方法就可以了。其他的不做任何改变。
策略设计模式
自定义一个类,但是所有的功能都已经完成,返回结果是,不知道用户需要怎么样的结果,这个参数由用户调用这个类是用户自己传递,而自定义类时,只是将这个参数封装成一个接口,用户自己去实现,自己去定义返回什么样的结果。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2