单例模式:就是一个类最多有一个实例对象
public class Singleton {
// volatile 避免指令重排
private volatile Singleton instance;
private Singleton() {}
public Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class){
if (instance == null) {
instance = new Singleton();
return instance;
}
}
}
return instance;
}
}
// 线程不安全版本
// 参考链接
//public class Singleton {
// private Singleton instance;
// private Singleton() {}
//
// public Singleton getInstance() {
// if (instance == null) {
//
// instance = new Singleton();
// return instance;
// }
// return instance;
// }
//}
网友评论