1 public class Singleton {
2 private static Singleton INSTANCE = null;
3
4 // Private constructor suppresses
5 private Singleton() {
6 initialize();
7 }
8
9 protected void initialize() {
10 // Your code here
11 }
12
13 //synchronized creator to defend against multi-threading issues
14 //another if check here to avoid multiple instantiation
15 private synchronized static void createInstance() {
16 if (INSTANCE == null) {
17 INSTANCE = new Singleton();
18 }
19 }
20
21 /**
22 * @return The unique instance of this class.
23 */
24 public static Singleton getInstance() {
25 if (INSTANCE == null) {
26 createInstance();
27 }
28 return INSTANCE;
29 }
30 }
double-checked locking 문제를 피해가는 방법
1 class Singleton {
2 private Vector v;
3 private boolean inUse;
4 private static Singleton instance = new Singleton();
5
6 private Singleton() {
7 v = new Vector();
8 inUse = true;
9 //...
10 }
11
12 public static Singleton getInstance() {
13 return instance;
14 }
15 }
참조: Singleton_pattern, http://www-128.ibm.com/developerworks/java/library/j-dcl.html
