public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton(){
System.out.println("生成一个实例");
}
public static Singleton getInstance(){
return singleton;
}
}
/**
* 最多生成3个实例,可根据编号获取实例
*/
public class Singleton3 {
private static Singleton3[] list = new Singleton3[]{ //生成类的实例时被初始化,只会生成一次
new Singleton3(0),
new Singleton3(1),
new Singleton3(2),
};
private int id;
private Singleton3(int id){
this.id = id;
System.out.println("生成一个实例:"+id);
}
public static Singleton3 getInstance(int id){
return list[id];
}
@Override
public String toString() {
return "::"+id;
}
}
public class Main {
public static void main(String[] args) throws ParseException {
// Singleton s1 = Singleton.getInstance();
// Singleton s2 = Singleton.getInstance();
// System.out.println(s1==s2);
for (int i = 0; i < 9; i++) {
Singleton3 instance = Singleton3.getInstance(i % 3);
System.out.println(i+":"+instance);
}
}
}
Singleton其它用法参考