public class Singleton {
/*
* 单例模式
* 第一种
* 优:线程安全
* 缺:类加载即创建,空间问题
*/
private static Singleton text=new Singleton();
private Singleton() {}
public static Singleton getInstance (){
return text;
}
}
public class Singleton2 {
/*单例模式
* 第二种
* 优:按需创建
* 缺:非线程安全,(假设A B 两个线程,A走过分支语句在创建text,
* 此时B线程进入分支,就可能创建两个text
*
*/
private static Singleton2 text=null;
private Singleton2 (){};
public static Singleton2 getInstance(){
if(text==null)
text=new Singleton2();
return text;
}
}
注:需要注意的是,由于我们把构造函数声明为私有,只能通过getInstance()把text送出,
所以getInstance()必须声明为static