设计模式-单例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
public class P66{
private static void main(String []args) {
for (int i = 0; i < 10000; i++) {
new Thread(() -> {
Singleton.getInstance().doSth(); // ok, only create one instance
// Singleton.getInstance2().doSth(); // error, will create more than one instance
// Singleton.getInstance3().doSth(); // error, will create more than one instance, too
// Singleton.getInstance4().doSth(); // error, maybe cause NullPointerException
}).start();
}
}

private static class Singleton {
private static Singleton instance;
private static int count;

private Singleton() {
count = count + 1;
if (count > 0) {
System.out.println(count);
}
}

private void doSth() {
// do something
}

// double check
public static Singleton getInstance() {
if (instance == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}

public static Singleton getInstance2() {
if (instance == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new Singleton();
}
return instance;
}

public static Singleton getInstance3() {
if (instance == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (Singleton.class) {
instance = new Singleton();
}
}
return instance;
}

public static Singleton getInstance4() {
if (instance == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}

if (count > 0) {
return instance;
} else {
instance = new Singleton();
}
}
return instance;
}
}
}