版本1
package com.dp;
public class Singleton {
private Singleton() {
// TODO Auto-generated constructor stub
}
private static Singleton instance = new Singleton();
private static Singleton getInstance() {
return instance;
}
}
版本2 较版本1,实现了懒加载
package com.dp;
public class Singleton {
private Singleton() {
// TODO Auto-generated constructor stub
}
private static Singleton instance = null;
private static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
版本3 较版本2,优化了同步带来的性能损耗
package com.dp;
public class Singleton {
private Singleton() {
// TODO Auto-generated constructor stub
}
private static class SingletonHolder {
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}