单例模式(Singleton Pattern)用来创建独一无二的,只能有一个实例的对象的入场券。
经典的单例模式,不考虑多线程:
public class Singleton {
private static Singleton uniqueInstance;//使用静态变量来记录Singleton类的唯一实例
// other useful instance variables here
private Singleton() {}//私有构造器,确保不能new对象
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
处理多线程:
1、将getInstance()方法变成同步(synchronized)方法。但是性能会大大下降
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
2、使用JVM来确保加载这个类的唯一单件实例
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return uniqueInstance;
}
}
3、使用双重检查枷锁,使用这个可以帮助大大减少getInstance的时间浪费,因此会先进行判断实例是否已经创建
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
参考资料《Head First设计模式》