单例模式(Singleton Pattern)

单例模式:

  和new类似,用来创建实例。

  单例对象的类保证了只有一个实例存在。

原理:

  1、该类的构造函数定义为私有方法,这样外面不能通过new实例化此类,只能在类里面实例化

  2、类返回一个获取实例的方法

构建方式:

  懒汉方式:全局的单例实例在第一次被使用是创建

  饿汉方式:全局的单例实例在类装载时构建

维基百科code例子:

饿汉方式创建:

  public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
  
    // Private constructor suppresses   
    private Singleton() {}
 
    // default public constructor
    public static Singleton getInstance() {
        return INSTANCE;
    }
  }

懒汉方式创建:

  public class Singleton {
    private static volatile Singleton INSTANCE = null;
  
    // Private constructor suppresses 
    // default public constructor
    private Singleton() {}
  
    //thread safe and performance  promote 
    public static  Singleton getInstance() {
        if(INSTANCE == null){
             synchronized(Singleton.class){
                 //when more than two threads run into the first null check same time, to avoid instanced more than one time, it needs to be checked again.
                 if(INSTANCE == null){ 
                     INSTANCE = new Singleton();
                  }
              } 
        }
        return INSTANCE;
    }
  }
原文地址:https://www.cnblogs.com/Mr-Wenyan/p/10208025.html