Java单例模式的5种实现方法

  • 饿汉
  • 懒汉-(线程安全)
  • 双重校验锁
  • 静态内部类
  • 枚举

Java单例模式的5种实现方法

饿汉

类加载的时候就创建了实例

优点:类加载的时候创建一次实例,避免了多线程同步问题
缺点:即使单例没被用到也会创建,浪费内存

1
2
3
4
5
6
7
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
}

懒汉-(线程安全)

缺点:性能问题,添加了synchronized的函数比一般方法慢得多,若多次调用getInstance,则累积的性能损耗特别大。

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

双重校验锁

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

静态内部类

1
2
3
4
5
6
7
8
9
10
public class StaticSingleton {
private StaticSingleton() {}
private static class SingletonHolder {
private static StaticSingleton INSTANCE = new StaticSingleton();
}

public static getInstance() {
return SingletonHolder.INSTANCE;
}
}

枚举

调用方式:Singleton.INSTANCE.getInstance()

1
2
3
4
5
6
7
8
9
10
11
12
13
class Resource{
}

public enum Singleton {
INSTANCE;
private Resource instance;
Singleton() {
instance = new Resource();
}
public Resource getInstance() {
return instance;
}
}