zoukankan      html  css  js  c++  java
  • 回调函数2

    上面一篇介绍了一下对回调函数的基本理解和一个简单的比较抽象的例子,那么下面通过一个比较实际的例子来看看对回调函数的运用
     
    比如现在我们要写一个测试类方法运行时间的程序,按照一般的程序思维,我们会写出下面的代码
    1. public   class  TestTime {  
    2.     /**  
    3.      * 一个用来被测试的方法,进行了一个比较耗时的循环  
    4.      */   
    5.     public   static   void  testMethod(){  
    6.         for ( int  i= 0 ; i< 100000000 ; i++){  
    7.               
    8.         }  
    9.     }  
    10.     /**  
    11.      * 一个简单的测试方法执行时间的方法  
    12.      */   
    13.     public   void  testTime(){  
    14.         long  begin = System.currentTimeMillis(); //测试起始时间   
    15.         testMethod(); //测试方法   
    16.         long  end = System.currentTimeMillis(); //测试结束时间   
    17.         System.out.println("[use time]:"  + (end - begin)); //打印使用时间   
    18.     }  
    19.       
    20.     public   static   void  main(String[] args) {  
    21.         TestTime test=new  TestTime();  
    22.         test.testTime();  
    23.     }  
    24. }  
        相 信上面写法大家都能看懂,这个写法也是大家都能写出来的,但是现在我们换个角度,我们最开始的要求就是测试方法的运行时间,也就是我们现在要完成的工作就 是测试运行时间,但是具体是什么方法,可以随便你给出来,很显然上面的写法就太死板了一些。我们可以这样子改改,让程序马上灵活起来首先我们可以先建立一个回调接口:
    1. public   interface  CallBack {  
    2.     //执行回调操作的方法   
    3.     void  execute();  
    4. }  

            然后后定义一个工具类:
    1. public   class  Tools {  
    2.       
    3.     /**  
    4.      * 测试函数使用时间,通过定义CallBack接口的execute方法  
    5.      * @param callBack  
    6.      */   
    7.     public   void  testTime(CallBack callBack) {  
    8.         long  begin = System.currentTimeMillis(); //测试起始时间   
    9.         callBack.execute(); ///进行回调操作   
    10.         long  end = System.currentTimeMillis(); //测试结束时间   
    11.         System.out.println("[use time]:"  + (end - begin)); //打印使用时间   
    12.     }  
    13.       
    14.     public   static   void  main(String[] args) {  
    15.         Tools tool = new  Tools();  
    16.         tool.testTime(new  CallBack(){  
    17.             //定义execute方法   
    18.             public   void  execute(){  
    19.                 //这里可以加放一个或多个要测试运行时间的方法   
    20.                 TestTime.testMethod();  
    21.             }  
    22.         });  
    23.     }  
    24.       
    25. }  
            注 意看上面这段代码testTime方法的第9行,只是直接调用了接口的方法,而当我们想要用这个测试工具测试程序运行时间的时候,那么就只需要像main 方法里面一样,调用testTime方法的时候去实现CallBack接口的execute()方法,也就是说再你调用的时候你想在里面写什么方法都 ok,而最后testTime方法会帮你测试出你这个方法所需要的时间,这样就在java里面其实就用了简单的一个多态的概念而达到了回调函数的作用。通 过上面的列子,看看是不是你这个测试时间的程序就写得更加灵活了呢?
     
  • 相关阅读:
    Codeforces Round #592 (Div. 2)C. The Football Season(暴力,循环节)
    Educational Codeforces Round 72 (Rated for Div. 2)D. Coloring Edges(想法)
    扩展KMP
    poj 1699 Best Sequence(dfs)
    KMP(思路分析)
    poj 1950 Dessert(dfs)
    poj 3278 Catch That Cow(BFS)
    素数环(回溯)
    sort与qsort
    poj 1952 buy low buy lower(DP)
  • 原文地址:https://www.cnblogs.com/cd-snoopy/p/3717816.html
Copyright © 2011-2022 走看看