Created
June 17, 2014 03:00
-
-
Save ixiyang/860070d1846feeaad20a to your computer and use it in GitHub Desktop.
Singleton pattern example
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
/** | |
* | |
* thread-safe | |
* | |
*/ | |
public class Singleton { | |
private static final Singleton INSTANCE = new Singleton(); | |
private Singleton() { | |
} | |
public static Singleton getInstance() { | |
return INSTANCE; | |
} | |
} | |
/** | |
* | |
* lazy init non-thread-safe | |
* | |
*/ | |
public class Singleton { | |
private static Singleton sInstance; | |
private Singleton() { | |
} | |
public static Singleton getInstance() { | |
if (sInstance == null) { | |
sInstance = new Singleton(); | |
} | |
return sInstance; | |
} | |
} | |
/** | |
* | |
* lazy init thread-safe low performance | |
* | |
*/ | |
public class Singleton { | |
private static Singleton sInstance; | |
private Singleton() { | |
} | |
public synchronized static Singleton getInstance() { | |
if (sInstance == null) { | |
sInstance = new Singleton(); | |
} | |
return sInstance; | |
} | |
} | |
/** | |
* | |
* lazy init & thread-safe (Java 5 or later) | |
* | |
*/ | |
public class Singleton { | |
private volatile static Singleton sInstance; | |
private Singleton() { | |
} | |
public static Singleton getInstance() { | |
if (sInstance == null) { | |
synchronized (Singleton.class) { | |
if (sInstance == null) { | |
sInstance = new Singleton(); | |
} | |
} | |
} | |
return sInstance; | |
} | |
} | |
/** | |
* | |
* lazy init & thread-safe (for all Java version) | |
* | |
*/ | |
public class Singleton { | |
private Singleton() { | |
} | |
private static class SingletonHolder { | |
private static final Singleton INSTANCE = new Singleton(); | |
} | |
public static Singleton getInstance() { | |
return SingletonHolder.INSTANCE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment