单例模式常用写法

目录
  1. 方法一:懒汉
  2. 方法二:饿汉
  3. 方法三:双重校验锁定
  4. 方法四:枚举
  5. 方法五:静态内部类

方法一:懒汉

在调用取得实例的方法时才会实例化对象

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

方法二:饿汉

在单例类被加载时候完成实例化

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

方法三:双重校验锁定

懒汉升级版,JDK1.5后生效,毕竟getInstance上的synchronized多数情况都没有用

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

方法四:枚举

1
2
3
4
5
public enum Singleton {  
INSTANCE;
public void mothed() {
}
}

方法五:静态内部类

1
2
3
4
5
6
7
8
9
public class Singleton {  
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}