代码
public class Singleton { private static Singleton singleton;//创建一个单例对象 public static Singleton getSingleton(){ if(singleton == null){//判断对象是否为空 singleton = new Singleton(); } return singleton; } }
public class Test { public static void main(String[] args) { Singleton s1 = Singleton.getSingleton(); Singleton s2 = Singleton.getSingleton(); System.out.println(s1 == s2); //输出true System.out.println(s1.equals(s2)); //输出true } }