1 最佳实践
Spring的Bean默认是单例的,方便Spring容器管理Bean的生命周期。如果采用非单例,则Bean初始化后交由JavaEE容器管理,Spring不再跟踪管理Bean的生命周期
2 代码
2.1 饿汉
class Singleton{
private static final Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getSingleton(){
return singleton;
}
}
2.2 懒汉
线程安全问题:在getSingleton2()上或方法内部增加synchronized关键字
class Singleton2{
private static Singleton2 single;
private Singleton2(){}
public static Singleton2 getSingleton2(){
if(single == null){
single = new Singleton2();
}
return single;
}
}
2.3 单例模式扩展:产生两个实例
class Singleton3{
private static int maxNum = 2;
private static ArrayList<Singleton3> singletonList = new ArrayList<Singleton3>();
private static int currentNum = 0;
static{
for(int i=0; i<maxNum; i++){
singletonList.add(new Singleton3());
}
}
private Singleton3(){}
public static Singleton3 getSingleton3(){
Random ran = new Random();
currentNum = ran.nextInt(maxNum);
return singletonList.get(currentNum);
}
}