1>单例类
package com.demo.singleton;
public class SingletonTest {
public static int num=0;//用于记录该类被实例化的次数
//声明一个类变量,外部代码想要得到SingletonTest对象,则返回该对象
private static SingletonTest st =null;
//将构造函数声明为private ,防止在外部代码直接new SingletonTest对象
private SingletonTest(){
num++;
System.out.println("SingletonTest()---"+num);
}
//得到SingletonTest类对象的方法
/*
*由于该类的构造方法声明为private的,所以不能在外部代码直接new一个该类的对象,
*所以也就不能调用实例方法,所以将getInsetance()方法声明为实例方法也就没有意义了,
*因为没有实例对象的话,也就不能调用该对象的实例方法。
*也是因为不能在外部直接new该类的对象,所以,外部能够访问该的方法只有类方法与类变量了,
*所以要将getInstance方法声明为类方法,也即static方法。
*/
public static SingletonTest getInstance (){
if(st==null){//当st对象不空时,创建一个
st=new SingletonTest();
}
System.out.println("getInstance ()----"+num);
return st;
}
}
2>测试类
package com.demo.singleton;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
SingletonTest st=null;
for(int i=0;i<10;i++){
System.out.println("index :"+i);
st=SingletonTest.getInstance();
}
}
}
输出: