单例模式的作用是使该类在全局中只存在一个实例。目的是当有其他类需要访问时,不需要重复创建该实例,并且可以共享该类数据。
1.饿汉式
public class Singleton {
private final static Singleton INSTANCE = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}
}
优点:在类加载时,就创建单例实例,避免的线程同步化。
缺点:可能后面不会使用该类,没有达到延迟加载,造成内存资源的浪费。
2.懒汉式
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
虽然起到了懒加载的作用,但是只能在单线程下使用。多线程使用可能导致创建多个实例。
3.双重检查式
public class Singleton {
private static volatile Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
优点:延迟加载,安全,效率高。
在实例化时,会先判断是否为空,在进一步加锁判断是否为空。如果实例化成功,后续调用该静态实例时,就不需要在进入加锁代码块。
4.静态内部类
public class Singleton {
private Singleton() {}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
该方法在类装载时,不会立即实例化,需要调用静态内部类后,才完成实例化。因为类的静态属性只会在类第一次加载的时候初始化,JVM保证了线程的安全性,在类初始化时,其他线程无法进入。