设计模式之单例模式


1. 什么是单例模式

确保一个类只有一个实例,并提供全局访问点.

2. 示例代码

3种单例模式代码.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 方法一
// 只有在类被使用的时候才会实例化, 每次getInstance都会产生大量额外开销, 所以getInstance的性能很差.
public class SingletonOne {

private static SingletonOne uniqueInstance;

private SingletonOne(){
}

public static synchronized SingletonOne getInstance(){
if(uniqueInstance == null){
uniqueInstance = new SingletonOne();
}
return uniqueInstance;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
// 方法二
// 在类被使用之前就创建好了实例, 其实我觉得, 一般情况下用这种就可以了.
public class SingletonTwo {
private static SingletonTwo uniqueInstance = new SingletonTwo();

private SingletonTwo() {
}

public static SingletonTwo getInstance(){
return uniqueInstance;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 方法三
// 只有在类被使用的时候才会实例化, 每次getInstance都会产生非常小的额外开销(判断逻辑), 但是相对于方法一, 开销已经小很多了.
public class SingletonThree {
private volatile static SingletonThree uniqueInstance;

private SingletonThree() {
}

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

3. 参考链接

<< Head First 设计模式 >>

谢谢你请我吃糖果!