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
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();