美文网首页
单例模式

单例模式

作者: 耗子撼大象 | 来源:发表于2017-09-30 09:25 被阅读0次

    饿汉式

    public class CustomerSingleton {

    private static CustomerSingleton single = new CustomerSingleton();
    private CustomerSingleton(){};
    public static CustomerSingleton getInstance(){
        return single;
    }
    

    懒汉式

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

    多线程内部类实现单例

    public class InnerSingleton {

    public static  class Singletion{
        private static Singletion single  = new Singletion();
    }
    public static Singletion getSingletion(){
        return Singletion.single;
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Singletion single1 = InnerSingleton.getSingletion();
        Singletion single2 = InnerSingleton.getSingletion();
        System.out.println(single1 +"===="+ single2);
    }
    

    }

    doubleSingleton

    public class DubbleSingleton {

    private static volatile DubbleSingleton ds;
    
    public  static DubbleSingleton getDs(){
        if(ds == null){
            synchronized (DubbleSingleton.class) {
                if(ds == null){
                    ds = new DubbleSingleton();
                }
            }
        }
        return ds;
    }

    相关文章

      网友评论

          本文标题:单例模式

          本文链接:https://www.haomeiwen.com/subject/telgextx.html