单件模式

经典单例模式

1
2
3
4
5
6
7
8
9
10
11
12
public class {
private static Singleton uniqueInstance;
private (){

}
public static Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}

处理多线程时

  1. 同步方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class {
private static Singleton uniqueInstance;
private (){

}

//这种方式会使运行效率大幅下降
public static synchronized Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
  1. “急切” 方式
1
2
3
4
5
6
7
8
public class {
private static Singleton uniqueInstance = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return uniqueInstance;
}
}
  1. “双重检查加锁”
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//jdk1.5 以后版本可用
public class Singleton{
private volatile static Singleton uniqueInstance;
private Singleton(){

}
public static Singleton getInstance(){
if(uniqueInstance == null){
synchronized (Singleton.class){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}