单例模式有5种实现方式,实现单例模式要掌握的要点:
1) 构造方法私有,为private
2) 确保单例类只有一个对象,尤其是多线程模式下
1.饿汉式
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return instance;
}
}
2.懒汉式,有两种写法
非线程安全的写法:
public class Singleton {
private static Singleton instance = null;
private Singleton(){
}
public static Singleton getInstance(){
if(instance==null){
instance = new Singleton();
}
return instance;
}
}
线程安全的写法:
public class Singleton {
private static Singleton instance = null;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(instance==null){
instance = new Singleton();
}
return instance;
}
}
3.双重检查加锁,实际中用的比较少,略过
4.静态内部类
public class Singleton {
private static class SingletonHolder{
/**
* 静态初始化,JVM保证线程安全
*/
private static Singleton instance = new Singleton();
}
private Singleton(){
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}
5.枚举
public enum Singleton{
INSTANCE;
}
如何选用:
多线程环境下,不能选用非线程安全的懒汉式,其他为线程安全的写法。
饿汉式与枚举为非懒加载,静态内部类与懒汉式为懒加载方式。
-单例对象 占用资源少,不需要延时加载,枚举 好于 饿汉
-单例对象 占用资源多,需要延时加载,静态内部类 好于 懒汉式
参考: