Java中的单利设计模式,是软件开发中最常用的设计模式之一。某个类在整个系统中只能有一个实例对象可以被获取和使用的代码模式。
例如:代表JVM运行环境的Runtime类。
(1) 某个类只能有一个实例
      构造器私有化
(2) 必须自行创建这个实例
      含有一个该类的静态变量来保存这个唯一的实例
(3) 必须自行向整个系统提供这个实例
      直接暴露(public); 用静态变量的get方法获取
直接创建对象,不存在线程安全问题
public class Singleton1(){
  public static final INSTANCE = new Singleton1();
  private Singleton1(){
  }
}
//表示该类型的对象是有限的几个
public enum Singleton2(){
 INSTENCE
}
public class Singleton3(){
  public static final INSTANCE;
  static{
    INSTANCE = new Singleton3();  
  }
  private Singleton3(){
  }
}
延迟创建对象
//提供一个静态方法来获取实例对象
public class Singleton4(){
  private  static final INSTANCE;
  private Singleton4(){
  }
  public Singleton4 getInstance(){
     if(INSTANCE == null){
    INSTANCE = new Singleton4();
  }
  return INSTANCE ;
  }
}
public class Singleton5(){
  private  static final INSTANCE;
  private Singleton5(){
  }
  if(INSTANCE == null){
    Synchronized(Singleton5.class){
      public Singleton4 getInstance(){
         if(INSTANCE == null){
        INSTANCE = new Singleton5();
      }
      return INSTANCE ;
      }
    }
  }
}
public class Singleton6(){
  private Singleton6(){
  }
  privated static class inner{
   public static final INSTANCE = new Singleton6();  
  }
  public static Singleton6 getInstance(){
    return INSTANCE;
  }
}
原文:https://www.cnblogs.com/lcy123/p/14960597.html