单例模式的实现

来源:互联网 发布:淘宝网掌柜名怎么改 编辑:程序博客网 时间:2024/06/05 18:35


单例模式的实现

  1. /**  
  2.  *   
  3.  * 单例模式的实现:饿汉式,线程安全 但效率比较低  
  4.  */  
  5. public class SingletonTest {   
  6.   
  7.     private SingletonTest() {   
  8.     }   
  9.   
  10.     private static final SingletonTest instance = new SingletonTest();   
  11.   
  12.     public static SingletonTest getInstancei() {   
  13.         return instance;   
  14.     }   
  15.   
  16. }  

  1. /** 
  2.  * 单例模式的实现:饱汉式,非线程安全  
  3.  *  
  4.  */  
  5. public class SingletonTest {  
  6.     private SingletonTest() {  
  7.     }  
  8.   
  9.     private static SingletonTest instance;  
  10.   
  11.     public static SingletonTest getInstance() {  
  12.         if (instance == null)  
  13.             instance = new SingletonTest();  
  14.         return instance;  
  15.     }  
  16. }  


0 0