单例模式

单例模式

单例模式在很多应用程序中有很多应用.比如说一个全局的工厂,一个threadlocal等等.要实现一个好的单利对象有很多种方法,可以挑选自己最喜欢的.

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


//饿汉式 在不要求一些性能方面可以这个样子
public class Simple {
private static Simple instance = new Simple();
private Simple(){
//
}
public static Simple getInstance() {
return instance;
}
}
//进阶 懒汉式 此方法可能导致并发的时候出现故障,比如很多线程在同事使用Two
class Two{
private static Two instance;
private Two(){
//
}
public static Two getInstance() {
if(instance==null){
instance = new Two();
}
return instance;
}
}

// 进阶 懒汉式 线程同步 这个线程同步没问题,但是会导致争用过大
class Three{
private volatile static Three instance;
private Three(){

}

public static synchronized Three getInstance(){
if(instance==null){
instance = new Three();
}
return instance;
}
}

// 进阶 良好的线程同步 双重检查
class Four{
private volatile static Four instance;
private Four(){

}

public static synchronized Four getInstance(){
if(instance==null){
synchronized (instance){
if(instance==null){
instance=new Four();
}
}

}
return instance;
}
}

// 静态内部类,懒汉式
class Five{
private Five(){

}

private static class SingleFactory{
private static Five instance = new Five();
}

public Five getInstance(){
return SingleFactory.instance;
}
}

// 枚举的单例模式 jdk1.5以后推荐
public enum singleton {
INSTANCE;
public singleton getInstance(){
return INSTANCE;
}
}