单例模式的作用:保证一个类只有一个实例,并提供一个访问他的全局访问点。用于解决一个全局使用的类被频繁创建和销毁。
1.六种方式的特点比较| 实现方式 | 是否线程安全 | 是否懒加载 | 实现难度 | 是否被反射破坏 | 性能 | 推荐程度 |
|---|---|---|---|---|---|---|
| 懒汉模式 | 否 | 是 | 易 | 是 | 优 | 不推荐 |
| 懒汉模式-加锁 | 是 | 是 | 易 | 是 | 差 | 不推荐 |
| 饿汉模式 | 是 | 否 | 易 | 是 | 优 | 推荐 |
| 双重检验锁 | 是 | 是 | 较复杂 | 是 | 良 | 推荐 |
| 静态内部类 | 是 | 是 | 一般 | 是 | 优 | 要求延迟加载时使用 |
| 枚举 | 是 | 否 | 一般 | 否 | 优 | 涉及反序列化时使用 |
public class Singleton{
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if( instance == null){
instance = new Singleton();
}
return instance;
}
}
懒汉模式-加锁
public class Singleton{
private static Singleton instance;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if( instance == null){
instance = new Singleton();
}
return instance;
}
}
饿汉模式
public class Singleton{
private static Singleton instance = new Singlenton();
private Singleton(){
}
public static Singleton getInstance(){
if( instance == null){
instance = new Singleton();
}
return instance;
}
}
双重校验锁
public class Singleton{
private volatile static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if( instance == null ){
synchronized(Singleton.class){
if( instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
静态内部类
public class Singleton{
private Singleton(){
}
public static Singleton getInstance(){
return InnerSingleton.INSTANCE;
}
private static class InnerSingleton{
private static final Singleton INSTANCE = new Singleton();
}
}
枚举
public class Singleton{
private Singleton(){
}
public static Singleton getInstance(){
return SingletonEnum.INSTANCE.getInstance();
}
private enum SingletonEnum{
INSTANCE;
private Singleton instance;
SingletonEnum(){
instance = new Singleton();
}
public Singleton getInstance(){
return instance;
}
}
}



