设计模式-单例模式

// 饿汉模式
public class Singleton{
  // 私有化默认构造函数,防止独自创建对象
  private Singleton(){
    
  }
  // 饿汉饿极了,上来直接就开'吃'了,虚拟机启动就创建实例对象
  private static Singleton instance = new Singleton();
  // 返回实例
  public static Singleton getInstance(){
    return instance;
  }
}

 

 

// 懒汉模式(多线程会出问题)
public class Singleton{
  // 私有化默认构造函数,防止独自创建对象
  private Singleton(){
    
  }
  // 懒汉比较懒,不创建实例对象,用的时候再创建
  private static Singleton instance;
  
  public static Singleton getInstance(){
    if(instance == null){
       instance = new Singleton();
    }
    return instance;
}

 

 

 

 

 

// 懒汉双检锁,避免多线程导致并发问题
pulblic class Singleton{
    private Singleton(){};

    private volatile static Singleton instance;

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

 

posted @ 2021-03-26 12:25  wsZzz1997  阅读(36)  评论(0编辑  收藏  举报