[u][b]懒汉[/b][/u] 调用getInstance方法时实例化
[b][u]饿汉[/u][/b] 类加载时实例化
[b][u]静态内部类[/u][/b] 调用getInstance方法时实例化
[b][u]枚举[/u][/b]
[b][u]双重校验锁[/u][/b]
Note:文章转自互联网
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if(null == instance) {
instance = new Singleton();
}
return instance;
}
}
[b][u]饿汉[/u][/b] 类加载时实例化
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
[b][u]静态内部类[/u][/b] 调用getInstance方法时实例化
public class Singleton {
private static class SingletonHolder {
private static final Singleton instance = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
[b][u]枚举[/u][/b]
public enum Singleton {
instance;
public void fun() {
//
}
}
[b][u]双重校验锁[/u][/b]
public class Singleton {
private volatile static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if(null == instance) {
synchronized (Singleton.class) {
if (null == instance) {
instance = new Singleton();
}
}
}
return instance;
}
}
Note:文章转自互联网