单例模式

    xiaoxiao2021-03-28  39

    单例模式

    七种单例模式写法的笔记

    public class Singleton { //1懒汉,线程不安全 // private static Singleton instance; // // private Singleton(){} // // public static Singleton getInstance(){ // if(null == instance){ // instance = new Singleton(); // } // return instance; // } //2懒汉,线程安全 // private static Singleton instance; // // private Singleton(){} // // public static synchronized Singleton getInstance(){ // if(null == instance){ // instance = new Singleton(); // } // return instance; // } //3饿汉 // private static Singleton instance = new Singleton(); // // private Singleton(){} // // public static Singleton getInstance(){ // return instance; // } //4饿汉 // private static Singleton instance = null; // static{ // instance = new Singleton(); // } // // private Singleton(){} // // public static Singleton getInstance(){ // return instance; // } //5静态内部类 // private static class intanceHolder{ // private static final Singleton INSTANCE = new Singleton(); // } // // private Singleton(){} // // public static final Singleton getInstance(){ // return intanceHolder.INSTANCE; // } //6枚举 // public enum Singleton{ // INSTANCE; // public void func(){ // // } // } //7双重检锁 // private static Singleton instance; // // private Singleton(){} // // public static Singleton getInstance(){ // if(null == instance){ // synchronized (Singleton.class) { // if(null == instance){ // instance = new Singleton(); // } // } // } // return instance; // } }
    转载请注明原文地址: https://ju.6miu.com/read-664636.html

    最新回复(0)