模板方式设计模式
  lo3R5ihTjlK9 2023年11月02日 20 0

模板方式设计模式

/**
* 统计不同操作的耗时,String拼接一万次的时间,int加和一万次的时间
* System.currentTimeMillis();获取当前时间
*/
public class IntDemo extends TimeTemplate {

    @Override
    public void doWork(){

        int num = 1;
        for (int i = 0; i < 1000000 ; i++) {
            num += 1;
        }

    }
}

public class StringDemo extends TimeTemplate {

    @Override
    public void doWork(){

        String str = "";
        for (int i = 0; i < 10000 ; i++) {
            str += 1;
        }

    }
}

//模板类
public abstract class TimeTemplate implements Time {

    final public long getTotalTime(){
        long begin = System.currentTimeMillis();

        this.doWork();

        long end = System.currentTimeMillis();
        return end - begin;
    }

public interface Time {
    /**
     * 统计时间的接口
     */
    void doWork();
}
    
public class Test {
    public static void main(String[] args) {
        StringDemo stringDemo = new StringDemo();
        long strTime = stringDemo.getTotalTime();
        System.out.println("str耗时:" + strTime);

        IntDemo intDemo = new IntDemo();
        long intTime = stringDemo.getTotalTime();
        System.out.println("int耗时:" + intTime);
    }
}

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  anLrwkgbyYZS   2023年12月30日   28   0   0 i++iosi++ioscici
  anLrwkgbyYZS   2023年12月30日   31   0   0 ideciciMaxideMax
lo3R5ihTjlK9
作者其他文章 更多

2023-12-08

2023-12-07

2023-12-05

2023-11-13

2023-11-02

2023-11-02

2023-11-02