单例模式的几种写法

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
// 饿汉模式
class God
{
private static God instance = new God();
private God(){}
public static God GetInstance
{
return instance;
}

}

// 懒汉模式
class God
{
private static God _godInstance = null;
private God(){}
public static God GetInstance()
{
if(_godInstance == null)
{
_godInstance = new God();
}
return _godInstance;
}
}

// 多线程
class God
{
private static God _godInstance = null;
private static object locker = new object();
private God(){}
private static God GetInstance()
{
if(_godInstance == null)
{
lock(locker)
{
if(_godInstance == null)
{
_godInstance = new God();
}
}
}
return _godInstance;
}
}