单例模式我们很熟悉,而且网上也有很多文章,不过有很多文章都是不对的,所以今天来总结一下,如果大家想去看原理,推荐大家去看Java并发编程的艺术这本书,这个里面会有很多原理的东西
版本1
private static Singleton single = null;
//不对,会重复创建
public static Singleton getInstance() {
if (single == null) {
single = new Singleton();
}
return single;
}
版本2
//对,但是非常影响性能,不推荐
public static synchronized Singleton getInstance2() {
if (single == null) {
single = new Singleton();
}
return single;
}
版本3
//不对,会重复创建,具体分析可以去看书
public static Singleton getInstance3() {
if (single == null) {
synchronized (Singleton.class) {
if (single == null) {
single = new Singleton();
}
}
}
return single;
}
版本4
//正确,即时加载
private static Singleton instance5 = new Singleton();
public static Singleton getInstance5() {
return instance5;
}
版本5
//正确,用了volatile关键字
private static volatile Singleton instance;
public static Singleton getInstance4() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
版本6
//正确,延时加载
private static class InstanceHolder {
public static Singleton instance = new Singleton();
}
public static Singleton getInstance6() {
return InstanceHolder.instance;
}
版本7
//正确,推荐使用
创建一个枚举类
public enum SingleEunm {
INSTANCE;
private Singleton instance;
SingleEunm() {
instance = new Singleton();
}
public Singleton getInstance() {
return instance;
}
}
然后用SingleEunm.INSTANCE.getInstance();进行调用
网友评论