/*
* 模式名称:单建模式
* 模式特征:只能创建该类的一个实例
* 模式用途:提供一个全局共享类实例
* */
package Creator.Singleton;
public class SingletonTest {
public static void main(String[] args){
SingletonTwo two1=SingletonTwo.getInstance();
SingletonTwo two2=SingletonTwo.getInstance();
System.out.println("two1=two2?"+(two1==two2));
System.out.println("two1.getNextID="+two1.getNextID());
System.out.println("two2.getNextID="+two2.getNextID());
System.out.println("two1.getNextID="+two1.getNextID());
}
}
class SingletonOne{
private SingletonOne(){};
public static SingletonOne instance=new SingletonOne();
public static synchronized SingletonOne getInstance(){
return instance;
}
//内部数据
private static int nextID=0;
public synchronized int getNextID(){
return ++nextID;
}
}
class SingletonTwo{
private SingletonTwo(){};
public static SingletonTwo instance=null;
public static synchronized SingletonTwo getInstance(){
if(instance==null){
instance=new SingletonTwo();
}
return instance;
}
//内部数据
private static int nextID=0;
public synchronized int getNextID(){
return ++nextID;
}
}