美文网首页
ddu-单例模式

ddu-单例模式

作者: 小董666 | 来源:发表于2016-07-13 16:06 被阅读0次
    • 饿汉式

        public class Singleton {
        private static final Singleton singleton=new Singleton();
       public Singleton getInstance(){
        return singleton;
         }
       }
      
    • 懒汉式

         class Singleton2{
         private  static Singleton2 mInstance ;
      
         public static Singleton2 getInstance(){
         if (mInstance==null){
           return new Singleton2();
             }
           return mInstance;
            }
         }
      
    • 方法加锁

        class Singleton3{
           private static Singleton3 mInstance;
      
           public static synchronized Singleton3 getInstance(){
           if (mInstance==null){
           mInstance= new Singleton3();
       }
       return mInstance;
         }
       }
      
    • Double Check Lock(DCL)

       class Singleton4{
       private static Singleton4 mInstance;
      
       public static  Singleton4 getInstance(){
       if (mInstance==null){
           synchronized(Singleton4.class){
               mInstance= new Singleton4();
           }
       }
       return mInstance;
         }
       }
      
    • 静态内部类单例模式

         class Singleton5{
      
           private static Singleton5 getInstance(){
           return Singleton5Holder.singleton5;
           }
       }
       class Singleton5Holder{
       public static Singleton5 singleton5=new Singleton5();
       }

    相关文章

      网友评论

          本文标题:ddu-单例模式

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