class Single
{
private Single(){}//私有化构造函数
private tatic Single s= new Single();//创建本类对象
public static Single getInstance()//提供访问方式
{
return s;//返回给访问者
}
}
实例:
class Single
{
private int num;
public void setnum(int num)
{
this.num = num;
}
public int getnum()
{
return num;
}
private Single(){}
private tatic Single s= new Single();
public static Single getInstance()
{
return s;
}
}
class SingleDome
{
public static void main(String[]args)
{
Single s1= Single.getInstance();
Single s2= Single.getInstance();
s1.stenum(23);
System.out.println(s2.getnum);//打印结果为23 此时ss,s1,s2都指向同一个对象
}
} |