public void setNum(int num)
{
this.num = num;
}
public int getNum()
{
return num;
}
//将构造函数私有化
private Single(){}
//在类中创建一个本类对象,因为构造函数被私有化,该类不能创建对象,想在外部访问,所以将其静态
private static Single s = new Single();
//提供一个方法可以获取到该对象,不能创建对象,所以将方法静态,可以通过:(类名.方法名)的形式进行访问
public static Single getInstance()
{
return s;
}
}
懒汉式:
class Single
{
private static Single s = null;
private Single(){}
public static Single getInstance()
{
if(s==null)
{
synchronized(Single.class)
{
if(s==null)
s = new Single();
}
}
return s;
}
}