设计模式——单例、适配器和工厂模式

设计模式

一、单例模式

单例模式: 在内存中存在(仅)有限的对象(一般是一个)。控制内存中对象存在的数量。

单例模式三种实现方式

懒汉式

特点:使用对象时,再创建对象。再多线程环境下,线程不安全

两个线程(A,B)同时访问(1), A先访问,准备创建对象, B线程来到(1),判断 instance ==null ,也准备创建对象。

public class Singleton{
   

   private static Singleton instance = null; 
   private Singleton(){
   } //先把构造方法初始化,防止被调用创建对象
    
   public static Singleton getInstance(){
   
       
       if(instance == null){
      // (1)
           instance = new Singleton();//(2)
       }
       return instance;
   }

}

如何保证线程安全?
第一种方式,在方法前面加同步锁synchronized。把每个线程都锁住 ,一个个判断是否为空,比较浪费时间。

public class Singleton{
   

   private static Singleton instance = null;
   private Singleton(){
   }
    
   public static synchronized Singleton getInstance(){
   
       
       if(instance == null){
      
           
           instance = new Singleton();
       }
       return instance;
   }

}

第二种方式 :双重检测模式
优点: 延迟加载

public class Singleton{
   

   private static volitle Singleton instance = null; //需要增加线程可见性volitle,假设创建完了,另一个线程就不再创建对象
   private Singleton(){
   }
    
   public static  Singleton getInstance(){
   
       
       if(instance == null){
            
           synchronized(Singleton.class){
    //锁住calss对象
               if(instance==null){
   
                  instance = new Singleton();   
               }
           }
       }
       return instance;
   }

}
饿汉式

先创建对象。JVM类加载器只会加载一次static对象,所以是线程安全的哦

public class Singleton{
   

   private static Singleton instance = new Singleton();
   private Singleton(){
   }
    
   public static Singleton getInstance(){
   
       return instance;
   }

}
枚举式

枚举的底层也是一个static静态对象
详见另一篇博客

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值