设计模式之单例模式
这是设计模式系列的第一篇——单例模式,记录自己的学习过程,也希望对你有帮助。如有错误,请批评指出,谢谢!!!
单例对象通俗的讲就是让一个类只构建一个对象。
- 非线程安全单例模式
public class singleton { //单例模式类
private singleton () {} //私有构造函数
private static singleton instance = null; //单例对象
public static singleton getInstance () { //静态get单例的方法
if (instance == null) {
instance = new singleton; //如果单例对象为空创建一个单例对象
}
return instance;
}
}
- 线程安全单例模式低级版
public class singleton { //单例模式类
private singleton () {} //私有构造函数
private static singleton instance = null; //单例对象
public static singleton getInstance () { //静态get单例的方法
if (instance == null) {
synchronized (this) { //增加同步锁,保证线程安全
if (instance == null) { //这里做两次判空是因为如果两个线程同时走到了上一个if (instance == null),其中一个线程先加锁执行,另一个线程已经做完第一个判空,如不做第二次判空,还是会构建对象
instance = new singleton; //如果单例对象为空创建一个单例对象
}
}
}
return instance;
}
}
- 线程安全单例模式高级版
public class singleton { //单例模式类
private singleton () {} //私有构造函数
private volatile static singleton instance = null; //volatile关键字防止指令重排,保证线程访问的变量值是主内存中的最新值
public static singleton getInstance () { //静态get单例的方法
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = new singleton; //如是低级版,可能由于JVM的指令重排导致不是完全线程安全的
}
}
}
return instance;
}
}