特别喜欢这个例子,现在拿出来分享给大家:
public class SingletonTest {
public static void main(String[] args){
Singleton s1=Singleton.getInstance();
Singleton s2=Singleton.getInstance();
System.out.println("s1=s2?"+(s1==s2));
System.out.println("s1.getNextID="+s1.getNextID());
System.out.println("s2.getNextID="+s2.getNextID());
System.out.println("s1.getNextID="+s1.getNextID());
}
}
class Singleton{
private static int nextID=0;
private static Singleton instance=null;
private Singleton(){};
public static synchronized Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
//内部数据
public synchronized int getNextID(){
return ++nextID;
}
}