Last active
August 29, 2015 14:00
-
-
Save Silvenga/1a9e989c2f3abfb7e2a6 to your computer and use it in GitHub Desktop.
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
package com.silvenga.singleton; | |
import java.util.Random; | |
public class RandomSingleton | |
// Basic interface for a Singleton | |
public static Random getInstance() { | |
// Return the instance of Random created in RandomContainer | |
return Container.randomInstance; | |
} | |
// We use an enum for lazy loading. Load a new instance once and only when needed | |
// Making a Singleton this way prevents any attempt of making multiple instances | |
private static enum Container { | |
// Required to prevent compiler optimization | |
INSTANCE; | |
// When the Enum is first accessed it will create | |
// a static instance of Random | |
private static Random randomInstance = new Random(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment