单例模式

什么是单例模式?
    单例模式就是在全局过程中只存在一个唯一对象,就是单例。

如何实现单例模式?
    实现单例模式只需要把构造函数私有化,然后提供本类的静态属性,需要提供对应的静态方法来产生唯一的对象。

实现方式:
    1、饿汉式---如果这个属性在定义的时候就初始化了。
 public class ImageLoader{  
         private static ImageLoader instance = new ImageLoader();  
         private ImageLoader(){}  
         public static ImageLoader getInstance(){   
           return instance;   
      }  
    } 

    2、懒汉式---如果这个属性是在调用对应的方法的时候才初始化。
public class ImageLoader{  
         private static ImageLoader instance;  
         private ImageLoader(){}  
         public static synchronized ImageLoader getInstance(){   
                if(instance == null){   
                     instance = new ImageLoader();   
               }   
                return instance;  
          }  
    }

    3、Double CheckLock 实现单例,DCL也就双重锁判断机制。
public class ImageLoader{  
         private static ImageLoader instance;  
         private ImageLoader(){}  
         public static ImageLoader getInstance(){  
               if(instance == null){  
                       synchronized (ImageLoader.class){  
                            if(instance == null){  
                               instance = new ImageLoader();  
                               }  
                        }  
                 }   
                 return instance;   
            }  
    }  

    4、静态内部类实现。

public class ImageLoader{  
        private static class InnerInstance{  
           private static final ImageLoader instance = new ImageLoader();  
        }  
        private ImageLoader(){}  
        public static ImageLoader ImageLoader(){  
            return InnerInstance.instance;  
       }  
    }  
使用场景:避免某个类产生多个对象而消耗过多的资源,确保某个类在程序中只有一个实例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值