Created
April 24, 2018 07:01
-
-
Save bastienapp/2bd6cc7f3f2fd1005fd944e49c469a65 to your computer and use it in GitHub Desktop.
Exemple de Singleton en Java
This file contains hidden or 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
| public class SingletonClass { | |
| private static volatile SingletonClass sSoleInstance; | |
| //private constructor. | |
| private SingletonClass(){ | |
| //Prevent form the reflection api. | |
| if (sSoleInstance != null){ | |
| throw new RuntimeException("Use getInstance() method to get the single instance of this class."); | |
| } | |
| } | |
| public static SingletonClass getInstance() { | |
| //Double check locking pattern | |
| if (sSoleInstance == null) { //Check for the first time | |
| synchronized (SingletonClass.class) { //Check for the second time. | |
| //if there is no instance available... create new one | |
| if (sSoleInstance == null) sSoleInstance = new SingletonClass(); | |
| } | |
| } | |
| return sSoleInstance; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment