java單例形式4種應用方法分享。本站提示廣大學習愛好者:(java單例形式4種應用方法分享)文章只能為提供參考,不一定能成為您想要的結果。以下是java單例形式4種應用方法分享正文
1、Java Concurrency In Practice的List
public class Singleton {
private static class SingletonHolder {
public static Singleton resource = new Singleton();
}
public static Singleton getResource() {
return SingletonHolder.resource ;
}
private Singleton(){
}
}
2、effective Java
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
private Singleton(){}
public void method(){
//...
}
public static void main(String[] a){
//挪用辦法。
Singleton.INSTANCE.method();
}
}
3、應用列舉奇妙創立單實例
/**
* 應用列舉奇妙創立單實例
*/
public enum Singleton {
INSTANCE;
public void method(){
//...
}
public static void main(String[] a){
//挪用辦法。
Singleton.INSTANCE.method();
}
}
4、兩重鎖
public class Singleton {
private static volatile Singleton instance = null;
/**
* 避免其別人new對象
*/
private Singleton(){
System.out.println("init");
}
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}