Singleton Pattern

1、单例模式:也叫单件模式,或单态模式。表示创建独一无二的(只有一个实例的)对象。
2、经典单例模式:延迟实例化(适用于非多线程)    
/**  
* @Class:classical signleton instance example:lazy instantiaze
* @Author:bufubuxing
* @Email:[email protected]
* @Date:2008/03/22
*/  
public class SingletonInstance{  
      
     //define a unique instance of this class by a static variable  
     private static Singleton uniqueInstance;  

     //private construct function  
     private SingletonInstance(){}  

     //getInstance: exist ? this : new  
     public static SingletonInstance getInstance(){  
           //lazy instantiaze
           if(uniqueInstance == null){  
               uniqueInstance = new SingletonInstance();  
          }  
           return uniqueInstance;  
     }  

     //TODO: Other somethings  
}
 
3、处理多线程单例模式:急切实例化(适用于多线程:编程简单,但过早实例化,增加负担)
/**
* @Class: multithreading Singleton Pattern Instance example:eagerly instantiaze
* @Author:bufubuxing
* @Email:[email protected]
* @Date:2008/03/22
*/
public class SingletonInstance{

     //eagerly instantiaze when JVM loading it
     private static Singleton uniqueInstance = new SingletonInstance();
    
     //private construct function
     private SingletonInstance(){}

     //getInstance
     public static SingletonInstance getInstance(){
         return uniqueInstance;
    }
   
    //TODO:Other somethings
}
 
4、处理多线程单例模式:同步getInstance()(适用于多线程:编程简单,但效率相当低)
/**
* @Class: multithreading Singleton Pattern instance example:synchronized getInstance()
* @Author:bufubuxing
* @Email: [email protected]
* @Date: 2008/03/22
*/
public class SingletonInstance{

   //define a static variable of this class
   private static SingletonInstance uniqueInstance;

   //private construct function
   private SingletonInstance(){}

   //getInstance():synchronized
   public static synchronized SingletonInstance getInstance(){
   //lazy instantiaze
   if(uniqueInstance == null){
      uniqueInstance = new SingletonInstance();
  }
   return uniqueInstance;
  }

   //TODO:Other somethings
}
 
5、处理多线程单例模式:双重检查锁(适用于多线程:效率较高,但JDK1.5以上支持)
/**
* @Class: multithreading Singleton Pattern instance example:double-checked locking  
* @Author:bufubuxing
* @Email:[email protected]
* @Date: 2008/03/22
*/
public class SingletonInstance{

     //volatile-lock checked:define a static variable of this class
     private volatile static SingletonInstance uniqueInstance;
    
     //private construct function  
     private SingletonInstance(){}

     //getInstance():synchronized-lock checked
     public static SingletonInstance getInstance(){ 
         //lazy instantiaze
        if(uniqueInstance == null){
             synchronized(SingletonInstance. class){
                 if(uniqueInstance == null){
                     uniqueInstance = new SingletonInstance();

                 }
             }    
        }
        return uniqueInstance;
    }

     //TODO:Other somethings
}
 

本文出自 “不服不行” 博客,转载请与作者联系!

你可能感兴趣的:(Pattern,职场,design,休闲)