*/
class Single{
private int num;
public void setNum(int num){
this.num = num;
}
public int getNum(int num){
return num;
}
private Single(){}
private static Single s=new Single();
public static Single getIntance(){
return s;
}
}
public class SingleDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//Single ss = Single.getIntance();
//Single s1 = new Single();
//Single s2 = new Single();
//s1.setNum(30);
//System.out.println(s2.getNum(0));
Single s1 = Single.getIntance();
Single s2 = Single.getIntance();
s1.setNum(23);
System.out.println(s2.getNum(0));
}
}
-------------------------------------------------------------------------------------------------------------------------
//对象是方法被调用时,才初始化,也叫做对象的延时加载 称为:懒汉式
//Single类进内存,对象还没存在,只有调用了getInstance方法时,才建立对象。
class Single2{
private static Single2 s = null;
private Single2(){}
public static Single2 getInstance(){
if (s==null)
s = new Single2();
return s;
}