一个理解“单例模式”最好的例子

特别喜欢这个例子,现在拿出来分享给大家:

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;
}
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注