-
Notifications
You must be signed in to change notification settings - Fork 0
单例模式
hawskpy edited this page Feb 23, 2018
·
2 revisions
单例模式(懒汉式)
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
这种写法线程不安全,改进一下,加一个同步锁:
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
网上这样的代码更多,可以很好的工作,但是缺点是效率低。 实际上,早在JDK1.5就引入volatile关键字,所以又有了一种更好的双重校验锁写法:
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
注意,别忘记volatile关键字哦,否则就是10重,100重也可能还是会出问题。 上面是用的最多的,还有一种静态内部类写法更推荐:
publlic class Singleton {
private Singleton() {}
private static class SingletonLoader {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonLoader.INSTANCE;
}
}