/*
懒汉式
对象时方法被调用时才初始化的,也叫延时加载
*/
class Demo
{
public static void main(String []args)
{
Single s1=Single.getInstence();//静态成员用类名调用。因为getInstence的返回值是个对象,所以s1是个对象
Single s2=Single.getInstence();
s1.setNum(23);//用对象调用函数
System.out.println(s2.getNum());
}
}
class Single
{
private int num;
public void setNum(int num)
{
this.num=num;
}
public int getNum()
{
return num;
}
private Single(){}
private static Single s=null;
public static Single getInstence()
{
if(s==null)
{
synchronized(Single.class)//synchronized是一个锁,条件
{
if(s==null)
{
s=new Single();
}
}
}
return s;
}
} |
|