Java Design Issue: Enforce method call sequence

后端 未结 12 578
青春惊慌失措
青春惊慌失措 2021-02-02 05:27

There is a question which was recently asked to me in an interview.

Problem: There is a class meant to profile the execution time of the code. The class

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-02 06:00

    This can also be done with Lambdas in Java 8. In this case you pass your function to the StopWatch class and then tell the StopWatch to execute that code.

    Class StopWatch {
    
        long startTime;
        long stopTime;
    
        private void start() {// set startTime}
        private void stop() { // set stopTime}
        void execute(Runnable r){
            start();
            r.run();
            stop();
        }
        long getTime() {// return difference}
    }
    

提交回复
热议问题