概述:
单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
特点:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一实例。
- 单例类必须给所有其他对象提供这一实例。
单例模式的几种写法:
饿汉式:不支持并发
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
懒汉式:不支持并发
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
注:懒加载很明显,但是在多线程不能正常工作。
懒汉式:支持并发(synchronized)
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public synchronized static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
注:懒加载很明显,并且能够在多线程中很好的工作。但效率很低。
双重校验锁:
public class Singleton {
private Singleton() {
}
private volatile static Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
注:实例必须有 volatile 关键字修饰,其保证初始化完全。
优点:懒加载,线程安全。
静态内部内:
public class Singleton {
private Singleton(){
}
private static class SingletonHolder{
private final static Singleton instance=new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}
优点:将懒加载和线程安全完美结合的一种方式(无锁)。(推荐)