单例模式续

Singleton (单例模式)

 

Intent Ensure a class only has one instance , and provide a global point of access of it.

 

瞎谈:就是保证一个类只有一个实例,并且提供一个全局可访问的点。打个比方,广州限制每户人家养狗,但是只能养一条。一开始你没有狗,你去买一条。若干年后,狗不行失踪了。你为了填补寂寞的空虚,别人又送你一条(或者还是你自己买的)。我们不关注你的狗来源,只保证你家的狗每时每刻就一条。你为了确保以后养狗方便,就到保险公司办了保险,他们承诺,你的狗要是出现意外事故,他们负责陪一条给你。从此,你自由了,狗的事情交给别人了,而且别人也保证只给一条给你。

 

正经:很多时候我们要保证类的实例只有一个。我们可能在自己的代码中判断需要的类的实例有无,无就new一个。这样看似不错。问题是,你用到这个类的地方有n个,这样你就需要n个判断。为什么不把这个职责交给类本身呢?然后让类提供一个接口访问

 

代码实现:

public class Singleton {

private static Singleton singleton=null;

private Singleton()  {}

public static Singleton instance(){

   if(singleton==null)

      singleton = new Singleton();

   return singleton

      return singleton;

}

}

 

有无问题:碰上多线程怎么办?凉拌了。加锁吧,或者。。。前人总结的经验,有3中方法

1.       直接加锁

 

public class Singleton{

private static Singleton singleton=null;

private Singleton() {}

public static synchronized Singleton instance(){

   if(singleton==null)

      singleton = new Singleton();

   return singleton

      return singleton;

}

}

 

 

 

 

2.       早期实例化

public class Singleton{

private static Singleton singleton = new Singleton();

private Singleton();

public static Singleton getInstance(){

   return singleton;

}

}

 

 

 

 

3.       双重检测锁

 

 
  •  
    1. public class Singleton   
    2.   
    3. {   
    4.   
    5.    private volatile static Singleton singleton=null;   
    6.   
    7.    private Singleton(){}   
    8.   
    9.    public static Singleton getInstance()   
    10.   
    11.    {   
    12.   
    13.               if(singleton==null)   
    14.   
    15.         {    synchronized(Singleton.class)   
    16.   
    17.                      {   
    18.                           if(singleton == null){   
    19.   
    20.                            singleton=new Singleton();   
    21.                            }   
    22.   
    23.                      }   
    24.   
    25.          }   
    26.   
    27.          return singleton;   
    28.   
    29.     }   
    30. }  
  •   
    
      
    
     
    

     
    

     4.还有一种线程安全的

     

     

     

    public class Singleton {   
      // Private constructor prevents instantiation from other classes   
      private Singleton() {}   
      
      /**  
       * SingletonHolder is loaded on the first execution of Singleton.getInstance()   
       * or the first access to SingletonHolder.INSTANCE, not before.  
       */  
      private static class SingletonHolder {    
        private static final Singleton INSTANCE = new Singleton();   
      }   
      
      public static Singleton getInstance() {   
        return SingletonHolder.INSTANCE;   
      }   
    }  
    

     

     

     

    你可能感兴趣的:(多线程,Access)