饿汉式:直接创建对象,不存在线程安全问题
- 直接实例化饿汉式(简洁直观)
- 枚举式(最简洁)
- 静态代码块饿汉式(适合复杂实例化):静态块内可以完成复杂的初始化
懒汉式:延迟创建对象
- 线程不安全(适用于单线程)
- 线程安全(适用于多线程)
- 静态内部类形式(适用于多线程)
代码实现
饿汉式
- 直接实例化饿汉式(简洁直观)
public class Singleton1 {
public static final Singleton1 INSTANCE = new Singleton1();
private Singleton1(){
}
}
- 枚举式(最简洁)
public enum Singleton2 {
INSTANCE
}
- 静态代码块饿汉式(适合复杂实例化)
public class Singleton3 {
public static final Singleton3 INSTANCE;
static {
INSTANCE = new Singleton3();
}
private Singleton3() {
}
}
懒汉式
- 线程不安全(适用于单线程)
public class Singleton4 {
private static Singleton4 instance;
private Singleton4(){
}
public static Singleton4 getInstance(){
if(instance == null){
instance = new Singleton4();
}
return instance;
}
}
- 线程安全(适用于多线程)
public class Singleton5 {
// 私有锁:不能暴露给其他业务(不能用类的class锁,因为这个锁可以被其他业务对象获取到)
private final static Object lock = new Object();
// 单例对象
private static volatile Singleton5 instance; // volatile 用于及时刷新属性值
private SingleTon5() {
}
/**
* 获取单例对象的方法:暴露给外界,用于获取实例
*/
public static Singleton5 getInstance() {
if (instance == null) {
synchronized (lock) {
if (instance == null) {
instance = new SingleTon5();
}
}
}
return instance;
}
}
- 静态内部类形式(适用于多线程)
public class Singleton6 {
private Singleton6() {
}
private static class Inner {
private static final Singleton6 INSTANCE = new Singleton6();
}
public static Singleton6 getInstance() {
return Inner.INSTANCE;
}
}