//懒汉模式 public class Singleton { //持有静态实例,防止被实例化,此处赋值为null,目的实现延迟加载 private static volatile Singleton instance = null; //私有构造方法,防止被实例化 private Singleton() { } // 懒汉式,静态工程方法,创建实例 public static Singleton getInstance() { if(instance == null) { synchronized (Singleton.class) { instance = new Singleton(); } } return instance; } }
饿汉模式
// 饿汉式 public class Singleton1 { //创建静态实例,防止被引用 private static Singleton1 instance = new Singleton1(); private Singleton1() { } private Singleton1 getInstance() { return instance; } }