1.懒汉式
public class Singleton { //2.创建实例对象 private static Singleton instance = null; //1.构造方法私有 private Singleton(){ } //3.公共的静态方法,返回实例 public static Singleton getInstance(){ if (instance==null){ instance = new Singleton(); } return instance; } }
2.饿汉式
private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return instance; }