java单例模式(懒加载)最好的实现方式?
请问大家都知道java的懒加载单例模式有哪些实现方式?我提出两种,一个是内部类实现方式:
public class Manager {
private Manager() {
}
public static Manager getInstance() {
return ManagerHolder.instance;
}
private static class ManagerHolder {
private static final Manager instance = new Manager();
}
}
一种是常用的方式:
public static class SingletonOptimizeLazy {
static SingletonOptimizeLazy instance = null;
public static SingletonOptimizeLazy getInstance() {
if (instance == null) {
createInstance();
}
return instance;
}
private synchronized static SingletonOptimizeLazy createInstance() {
if (instance == null) {
instance = new SingletonOptimizeLazy();
}
return instance;
}
}
那种方式是最好的,欢迎大家讨论啊!
Makeup
12 years, 11 months ago