单例模式

饿汉

public class Singleton {
    private  static final  Singleton instance = new Singleton();
    private Singleton(){};
    public static Singleton getInstance() {
        return instance;
    }
}

双检索

public class Singleton {
    private static volatile Singleton instance ;
    private Singleton(){};
    public static Singleton getInstance() {
        if(instance==null){
            synchronized(Singleton.class){
                if(instance==null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

枚举

根据枚举的实现原理是是继承enum接口的类,每个元素是static final的,所以枚举实现单例是线程安全的

public enum Singleton {
  INSTANCE;
}

包含信息

public enum Singleton {
    INSTANCE;
    private Resource instance;
    Singleton() {
        instance = new Resource();
    }
    public Resource getInstance() {
        return instance;
    }
}

静态内部类

静态内部类被调用时才被虚拟机加载,属于懒加载。缺点是加载class文件的时候需要额外消耗一点时间

class Singleton {
    private Singleton() {
        System.out.println("singleton create");
    }
    private static class InstanceHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    public static Singleton getInstance() {
        return InstanceHolder.INSTANCE;
    }
}

测试

public class Singleton {
    private Singleton() {
        System.out.println("singleton create");
    }
    private static class InstanceHolder {
        private static final Singleton INSTANCE = new Singleton();
        static{
            System.out.println(1);
        }
    }
    public static Singleton getInstance() {
        return InstanceHolder.INSTANCE;
    }
    public static void main(String ...arg){
        Singleton s = new Singleton();
        //Singleton.getInstance();
    }
}
//输出singleton create

你可能感兴趣的:(单例模式)