Java Design Issue: Enforce method call sequence

后端 未结 12 842
青春惊慌失措
青春惊慌失措 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 05:46

    I know this already has been answered but couldn't find an answer invoking builder with interfaces for the control flow so here is my solution : (Name the interfaces in a better way than me :p)

    public interface StartingStopWatch {
        StoppingStopWatch start();
    }
    
    public interface StoppingStopWatch {
        ResultStopWatch stop();
    }
    
    public interface ResultStopWatch {
        long getTime();
    }
    
    public class StopWatch implements StartingStopWatch, StoppingStopWatch, ResultStopWatch {
    
        long startTime;
        long stopTime;
    
        private StopWatch() {
            //No instanciation this way
        }
    
        public static StoppingStopWatch createAndStart() {
            return new StopWatch().start();
        }
    
        public static StartingStopWatch create() {
            return new StopWatch();
        }
    
        @Override
        public StoppingStopWatch start() {
            startTime = System.currentTimeMillis();
            return this;
        }
    
        @Override
        public ResultStopWatch stop() {
            stopTime = System.currentTimeMillis();
            return this;
        }
    
        @Override
        public long getTime() {
            return stopTime - startTime;
        }
    
    }
    

    Usage :

    StoppingStopWatch sw = StopWatch.createAndStart();
    //Do stuff
    long time = sw.stop().getTime();
    

提交回复
热议问题