class Singleton
{
private static Singleton instance; //使用instance变量来缓存曾经创建的实例
private Singleton(){} //隐藏该构造器,防止类自由创建对象
public static Singleton getInstance() //用public,static修饰,为了让main调用
{
if(instance==null) //如果未创建过对象
{
instance=new Singleton();
}
return instance;
}
}
public class TestSingleton
{
public static void main(String[] args){
//因为类Singleton的构造器被private修饰,导致构造器不能被同一包下的其他类访问;
//在调用getInstance()方法之前不存在对象,因此调用该方法的不可能是对象,而是类
Singleton s1=Singleton.getInstance();
Singleton s2=Singleton.getInstance();
System.out.println(s1==s2);
/*
使用"=="运算符比较两个引用类型的变量是否相同,必须都指向同一对象才返回true
使用Object类的实例方法比较两个字符串相等,只要字符串序列相同就返回true,对象可以不同
*/
}
}
java单例(SIngleton)类浅析
猜你喜欢
转载自blog.csdn.net/dyd850804/article/details/80968273
今日推荐
周排行