//模板类AbstractOperateTimeTemplate
abstract class AbstractOperateTimeTemplate
{
final public long getTime()
{
long begin = System.currentTimeMillis();
doWork();
long end = System.currentTimeMillis();
long time = end - begin;//所需时间
return time;
}
//抽象方法 子类必须覆盖
protected abstract void doWork();
}
//操作StringOperate
class StringOperate extends AbstractOperateTimeTemplate
{
protected void doWork()
{
String str = "";
for (int i = 0;i<=10000 ;i++ )
{
str += 1;
}
}
}
//操作IntOperate
class IntOperate extends AbstractOperateTimeTemplate
{
protected void doWork()
{
int str = 0;
for (int i = 0;i<=1000000 ;i++ )
{
str += 1;
}
}
}
//模板方法设计类
class TemplateMethodDemo
{
public static void main(String[] args)
{
StringOperate a1 = new StringOperate();
System.out.println(a1.getTime());
IntOperate a2 = new IntOperate();
System.out.println(a2.getTime());
}
}