经典模式
public class SingleTon {
private static SingleTon uniqueInstance;
//必须是私有
private SingleTon() {}
//线程不安全
public static SingleTon getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new SingleTon();
}
return uniqueInstance;
}
//这里是其他的有用方法
}
改进:
1. 同步getInstance():
public class SingleTon {
private static SingleTon uniqueInstance;
//必须是私有
private SingleTon() {}
public static synchronized SingleTon getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new SingleTon();
}
return uniqueInstance;
}
//这里是其他的有用方法
}
2 急切实例化:
public class SingleTon {
private static SingleTon uniqueInstance = new SingleTon();
//必须是私有
private SingleTon() {}
public static SingleTon getInstance() {
return uniqueInstance;
}
//这里是其他的有用方法
}
3 双重检查加锁
public class SingleTon {
private static volatile SingleTon uniqueInstance;
//必须是私有
private SingleTon() {}
public static SingleTon getInstance() {
if(uniqueInstance == null) {
synchronized (SingleTon.class) {
if(uniqueInstance == null) {
uniqueInstance = new SingleTon();
}
}
}
return uniqueInstance;
}
//这里是其他的有用方法
}