单例模式

class Singleton
{
// 使用一个类变量缓存曾经创建的实例
private static Singleton instance;
// 将构造器使用private修饰,隐藏该构造器
private Singleton(){}
// 提供一个静态方法,用于返回Singleton实例
// 该方法可以加入自定义的控制,保证只产生一个Singleton对象
public static Singleton getInstance()
{
// 如果instance为null,表明还不曾创建Singleton对象
// 如果instance不为null,则表明已经创建了Singleton对象,将不会执行该方法
if (instance == null)
{
// 创建一个Singleton对象,并将其缓存起来
instance = new Singleton();
}
return instance;
}

}

优点:减少创建java实例所带来的系统开销

会带来线程安全的问题

线程安全的单例模式

  1. public class Singleton{   
  2.     private static Singleton instance=null;   
  3.     private Singleton(){}   
  4.     public static synchronized Singleton getInstance(){   
  5.         if(instance==null){   
  6.             instance=new Singleton();   
  7.         }   
  8.         return instance;   
  9.     }   
  10. }   

  1. //懒汉式  
  2. class LSingle{  
  3.     private static  Instance _instance = null;   
  4.     private LSingle(){}  
  5.       
  6.     public static Instance getInstance(){  
  7.         if(_instance==null){  
  8.             synchronized(LSingle.class){  
  9.                 _instance = new Instance();  
  10.             }  
  11.         }  
  12.         return _instance;  
  13.     }  
  14. }  
  15. //饿汉式  
  16. class ESingle{  
  17.     private static Instance _instance = new Instance();  
  18.       
  19.     private ESingle(){}  
  20.       
  21.     public static Instance getInstance(){  
  22.         return _instance;  
  23.     }  
  24. }  

         如果实例在系统中不停的被用到,选用饿汉式是不错的选择


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章