1. 单线程可用
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getInstance() {
if (null == singleton) {
singleton = new Singleton();
}
return singleton;
}
}
2. 使用final常量
public class Singleton {
private static final Singleton singleton = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return singleton;
}
}
3. 加锁构造
public class Singleton {
private static Singleton singleton;
private static final Lock LOCK = new ReentrantLock();
private Singleton() {
}
public static Singleton getInstance() {
if (null == singleton) {
LOCK.lock();
if (null == singleton) {
singleton = new Singleton();
}
LOCK.unlock();
}
return singleton;
}
}
4. 方法级加锁
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getInstance() {
if (null == singleton) {
init();
}
return singleton;
}
private static synchronized void init(){
if(null == singleton){
singleton = new Singleton();
}
}
}
5. 静态内部类实现,多线程可用
public class Singleton {
private Singleton() {
}
public static Singleton getInstance() {
return Container.singleton;
}
private static class Container {
private static Singleton singleton = new Singleton();
}
}
6. 拒绝强行反射创建我
public class Singleton {
private Singleton() {
if (null != Container.singleton) {
throw new UnsupportedOperationException(); // 报错啦
}
}
public static Singleton getInstance() {
return Container.singleton;
}
private static class Container {
private static Singleton singleton = new Singleton();
}
}