Last active
August 16, 2020 13:22
-
-
Save yusufcakal/08fd28bd2b17d36a5b440cd69a93f591 to your computer and use it in GitHub Desktop.
freeze/unfreeze operations date in java / virtual clock pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Calendar; | |
import java.util.Date; | |
public final class Clock { | |
private static boolean isFrozen; | |
private static Date timeSet; | |
private Clock() { | |
} | |
public static synchronized void freeze() { | |
isFrozen = true; | |
} | |
public static synchronized void freeze(Date date) { | |
freeze(); | |
timeSet = date; | |
} | |
public static synchronized void unfreeze() { | |
isFrozen = false; | |
timeSet = null; | |
} | |
public static Date getTime() { | |
Calendar calendar = Calendar.getInstance(); | |
if (isFrozen) { | |
if (timeSet == null) { | |
timeSet = calendar.getTime(); | |
} | |
return timeSet; | |
} | |
return calendar.getTime(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment