单例模式

public class Singleton {

    private volatile static Singleton instance = null;

    

    private Singleton () {

    }

    

    public static Singleton getSingleton() {

        if(instance == null) {

            synchronized(Singleton.class) {

                if(instance == null) {

                    instance = new Singleton();

                }

            }

        }

        return instance;

    }

}


//jdk1.5前
public class Singleton { private static class SingletonInstance { private static final Singleton instance = new Singleton(); } private Singleton { } public static Singleton getSingleton() { return SingletonInstance.instance; } }

 

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