实现单例模式的几种方法

淺唱寂寞╮ 提交于 2020-03-08 04:33:21

单例模式(singleton):
某些类在进程的运行过程,只需要一个对象,不允许创建多个对象出来

如何写单例模式:

1.饿汉模式——一开始就创建好对象

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

2.懒汉模式——用到时再创建对象

1)线程不安全的懒汉模式

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

多线程时,线程不安全。——加锁,将方法加锁

2)双重锁的懒汉模式

class Singleton {
    private static  volatile Singleton instance = null;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
          sychronized(Singleton.class){
             if(instance == null){
               instance = new Singleton();
             }
        }
      }
     return instance;
    }
}
  • 不把锁加到if前面的原因:将锁加到if的前面,则在重复抢锁,加锁,不为空,释放锁
  • 需要进行二次判断的原因:抢锁的过程经历了很多,有可能已经创建好了对象
  • 还需加volatile-保证别人拿到的对象不是初始化一半的对象,而是准备好的对象。

3. 使用内部类实现单例模式(不考虑线程安全问题)

静态内部类实现单例模式-不考虑线程安全问题

class Singleton2{    
       private Singleton2(){  
       } 
       public static Singleton2 getInstance(){ 
           return UserSingletonHolder.INSTANCE;  
       }  
       private static class UserSingletonHolder{ 
           public static final Singleton2 INSTANCE = new Singleton2();    }
 }

4. 使用枚举实现单例模式(不考虑线程安全问题)

 //枚举实现单例模式
 enum Singleton3{  
   INSTANCE;//该对象已经是一个实例了    
   public Singleton3 getInstance(){ 
     return INSTANCE; 
     }
   }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!