标签:
class Singleton{ //使用一个变量来缓存曾经创建的实例 private static Singleton instance; //对构造器使用private修饰,隐藏该构造器 private Singleton(){} //该方法用来获取实例,保证只产生一个Singleton对象 public static Singleton getInstance(){ if(instance==null){ instance=new Singleton(); } return instance; } } public class SingletonTest { public static void main(String[] args) { Singleton s1=Singleton.getInstance(); Singleton s2=Singleton.getInstance(); System.out.println(s1==s2); } }
输出结果:true
标签:
原文地址:http://www.cnblogs.com/caoyc/p/5534279.html