单例模式(懒汉式和饿汉式)及优化

手写单例(饿汉式)

 1 class SingleObj{
 2     //私有变量 
 3     private static SingleObj single=new SingleObj();          
 4    //私有构造函数 不能被实例化  
 5     private static SingleObj(){}
 6 
 7     public static SingleObj getInstance(){
 8     return single;    
 9   }      
10 }

优点:没有加锁,执行效率更高

缺点:类加载时就初始化,浪费内存

懒汉式

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

优点:第一次调用才初始化,避免浪费内存

缺点:加锁了执行效率低

猜你喜欢

转载自www.cnblogs.com/tony-zhu/p/11504764.html
今日推荐