懒汉式

优点:在需要的时候才去加载
缺点:在多线程的环境下,会出现线性不安全的情况

1
2
3
4
5
6
7
8
9
10
11
public class Singleton {  
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

饿汉式

优点:饿汉式在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以天生是线程安全的

//饿汉式单例类.在类初始化时,已经自行实例化
public class Singleton {
//static修饰的静态变量在内存中一旦创建,便永久存在
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}

加双重锁

优点:在并发量不高、安全性不高的情况下可以很好的运行
缺点:在不同的编译环境下可能出现不同的问题

1
2
3
4
5
6
7
8
9
publci static synchronized Singleton getInstance(){
if(instance == null){
synchronized(Object){
if(instance == null){
instance = new Singleton();
}
}
}
}

内部类

优点:延迟加载、线性安全、减少内存消耗

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Singleton {  
/**
* 私有的构造器
*/
private Singleton() {
}
/**
* 内部类实现单例模式
* 延迟加载,减少内存开销
*
*/
private static class SingletonInner {
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonInner.instance;
}
}