holder :
资源利用高,不调用就不会被实例,反应不快。
public class Singleton{
???? private static?class SingletonHolder{
????? public final?static Singleton instance = new Singleton();
}
???? public static Singleton getInstance(){
????? return SingletonHolder.instance;
}
private Singleton(){}
}
-----------------------------------------------------------------------------------------
如果有请求需要Singleton则会判断如果当前没有创建Singleton则重新创建,如果已有则直接返回已创建的Singleton。资源利用较为不错,不调用就不会实例。既然如此第一次调用的时候加载肯定会需要一段时间,反应不是很快。
classical :
public class Singleton{
??? private static Singleton instance = null;
????private Singleton (){}
??? public static Singleton getInstance(){
???? if(instance==null){
???? instance = new Singleton();
}
??? return instance;
}
}
------------------------------------------------------------------------------------------
直接已静态形式创建Singleton,无论是否有需求都在类加载时创建,被调用时反应会很快,线程安全。如果永远都没被调用就悲剧了,这个对资源的利用太浪费了。
public class Singleton{
?? private Singleton(){}
?? private final static Singleton instance = new Singleton();
?? public static Singleton getInstance(){
??? returtn instance;
}
}
-------------------------------------------------------------------------------------------------------------
双检测:
不掉用getInstance方法就不会被实例,第一次加载反应慢。
public class Singleton(){
??? private staitc Singleton instance = null;
??? private Singleton(){}
???
??? public static Singleton getInstance(){
??? if(instance==null){
????? synchronized(Singleton.class){
???? if(instance==null){
???? instance = new Singleton();
}
}
}
returnn instance;
}
}