单例模式

单例模式分为三种:懒汉模式、饿汉模式、登记式模式

   

1.懒汉模式:


此例没有考虑到线程安全问题,是个简单的饿汉模式 

  1. public class Singleton {  
  2.     private Singleton() {}  
  3.     private static Singleton single=null;  
  4.     //静态工厂方法   
  5.     public static Singleton getInstance() {  
  6.          if (single == null) {    
  7.              single = new Singleton();  
  8.          }    
  9.         return single;  
  10.     }  
  11. }  




此例懒汉模式很好低解决了线程安全问题

  1. public class Singleton {    
  2.     private static class LazyHolder {    
  3.        private static final Singleton INSTANCE = new Singleton();    
  4.     }    
  5.     private Singleton (){}    
  6.     public static final Singleton getInstance() {    
  7.        return LazyHolder.INSTANCE;    
  8.     }    
  9. }    







2.饿汉模式:


  1. //饿汉式单例类.在类初始化时,已经自行实例化   
  2. public class Singleton1 {  
  3.     private Singleton1() {}  
  4.     private static final Singleton1 single = new Singleton1();  
  5.     //静态工厂方法   
  6.     public static Singleton1 getInstance() {  
  7.         return single;  
  8.     }  
  9. }  





3.登记式模式(本文忽略)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值