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(){
}
}
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
private Singleton(){}
public void method(){
//...
}
public static void main(String[] a){
//调用方法。
Singleton.INSTANCE.method();
}
}
/**
* 利用枚举巧妙创建单实例
*/
public enum Singleton {
INSTANCE;
public void method(){
//...
}
public static void main(String[] a){
//调用方法。
Singleton.INSTANCE.method();
}
}
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;
}
}