qiuzeliang
4/25/2018 - 12:22 PM

单例模式

public class Singleton { 
    private Singleton(){
    }
      public static Singleton getInstance(){  
        return SingletonHolder.sInstance;  
    }  
    private static class SingletonHolder {  
        private static final Singleton sInstance = new Singleton();  
    }  
}
public class Singleton {

    private static Singleton singleton;

    private Singleton(){}


    public static Singleton getSingleton(){
        synchronized(Singleton.class){
            if (singleton == null) { 
                singleton = new Singleton();
            }
        }
        return singleton;
    }
// 线程安全的懒汉式单例
public class Singleton {

    private static Singleton singleton;

    private Singleton(){}

    public static synchronized Singleton getSingleton(){
        if (singleton == null) {
            singleton = new Singleton2();
        }
        return singleton2;
    }
}
public class Singleton {

    private static Singleton singleton;

    private Singleton(){}

    public static Singleton getSingleton(){
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}
public class Singleton {
    private static Singleton singleton = new Singleton();
    
    private Singleton(){
        
    }
    
    public static Singleton getInstance(){
        return singleton
    }
}