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;
//构造器私有化
private Singleton(){}
//方法同步,调用效率低
public static synchronized Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
}
3.Double CheckLock实现单例:DCL也就是双重锁判断机制(由于JVM底层模型原因,偶尔会出问题,不建议使用)
public class Singleton {
private volatile static Singleton instance;
private Singleton() {
}
public static Singleton newInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
4.静态内部类实现模式(线程安全,调用效率高,可以延时加载)
public class Singleton {
private static class SingletonHolder{
private static final Singleton instance=new Singleton();
}
private Singleton(){}
public static Singleton getInstance(){
return SingletonClassInstance.instance;
}
}
5.枚举类(线程安全,调用效率高,不能延时加载,可以天然的防止反射和反序列化调用)
public enum Singleton {
//枚举元素本身就是单例
INSTANCE;
//添加自己需要的操作
public void singletonOperation(){
}
}
网友评论