设计模式之单例模式

1.单例模式特点

     (1).单例类只能有一个实例。

 (2).单例类必须自己创建自己的唯一实例。

 (3).单例类必须给所有其他对象提供这一实例。

2.单例模式的几种实现方式

    (1)饿汉式

 public class Singleton {
     private static Singleton instance = new Singleton(); //直接初始化一个实例对象
     private Singleton(){                 //private类型的构造函数,保证其他类对象不能直接new一个该对象的实例
     }
     public static Singleton getInstance(){  //该类唯一的一个public方法    
         return instance;
     }
 }

 

     上述代码中的一个缺点是该类加载的时候就会直接new 一个静态对象出来,当系统中这样的类较多时,会使得启动速度变慢 。现在流行的设计都是讲“延迟加载”,我们可以在第一次使用的时候才初始化第一个该类对象。所以这种适合在小系统。 


   (2)懒汉式(线程安全)

  public class Singleton {  
       private static Singleton instance = null;  
       private Singleton (){
           
       }   
       public static synchronized Singleton getInstance(){    //对获取实例的方法进行同步
         if (instance == null)     
           instance = new Singleton(); 
         return instance;
      }
  }  

      将instance方法加上synchronized进行限定,确实可以解决线程安全问题,但会造成多线程调用该方法时串行执行,效率低下,如何改进呢?以下代码既可以保证线程安全又可以提高多线程并发的效率。

   (3)多线程安全单例(双重同步锁)

 public class Singleton {  
      private static Singleton instance = null;  
      private Singleton (){
      }   
      public static Singleton getInstance(){    //对获取实例的方法进行同步
        if (instance != null){
	    return instance;
   	}
        synchronized(Singleton.class){
            if (instance == null)
                instance = new Singleton(); 
        }
        return instance;
      }
      
  }


       或者这么写:

 public class Singleton {  
      private static Singleton instance = null;  
      private Singleton (){
      }   
      public static Singleton getInstance(){    //对获取实例的方法进行同步
        if (instance == null){
            synchronized(Singleton.class){
                if (instance == null)
                    instance = new Singleton(); 
            }
        }
        return instance;
      }
      
  }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值