package single;
// 单例设计模式
// 直接调用的时候就初始化好,懒
public class Singleton {
// 饿汉,没有线程安全问题,但是性能低
private static final Singleton instance = new Singleton();
// 构造器私有化,防止new
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
// 饿汉模式,方法一
public class Singleton {
// volatile保证线程间的可见性
private static volatile Singleton INSTANCE;
// 构造器私有化,防止new
private Singleton() {
}
// 直接锁下面的方法
public static synchronized Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
// 饿汉模式,方法二
public class Singleton {
// volatile保证线程间的可见性
private static volatile Singleton INSTANCE;
// 构造器私有化,防止new
private Singleton() {
}
// 双重检查锁
public static Singleton getInstance() {
if (INSTANCE == null) {
// 只有一个线程能拿到锁
synchronized (Singleton.class) {
// 如果在创建的好了单例的时候,其他线程阻塞在创建对象的外面,这时候需要再判断一下该单例对象是否为空
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
// 饿汉模式,方法三
public class Singleton {
// 构造器私有化,防止new
private Singleton() {
}
// 利用static性质:创建只有一次
private static class Holder {
// volatile保证线程间的可见性
private final static Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}