单例设计模式

下面是单例设计模式的两种设计方式

饿汉式:使用的时候多用,同步的,可以保证唯一性

public class Singleton {//饿汉式

    private static Singleton s = new Singleton();

    private Singleton(){}   

    public static Singleton getInstance(){

       return s;

    }

}

懒汉式:考试的时候多用,非同步的,不能保证唯一性,涉及同步问题,考点较多

public class Singleton{//低效率懒汉式

    private static Singleton s = null;

    private Singleton(){}   

    public static synchronized Singleton getInstance(){

       if(s==null)

           s = new Singleton();

       return s;

    }

}

 

public class Singleton{//高效率懒汉式

    private static Singleton s = null;

    private Singleton(){}   

    public static Singleton getInstance(){

       if(s==null){

           synchronized(Singleton.class){

               if(s==null)

                  s = new Singleton();

           }         

       }

       return s;        

    }

}

原文地址:https://www.cnblogs.com/talkice/p/3352804.html