什么是单例
整个系统中某个类只有一个实例。
单例有什么用
单例相当于是系统的一个全局变量。
应用场景:系统的配置信息存放于文件中,通过一个类的单例对象读取配置文件,有利于整个系统对配置信息的统一调度管理。
(还有哪些应用场景?)
java 单例实现
饿汉式,在类加载时构建单例对象
public class Singleton {
private static Singleton instance = new Singleton(); // 有人在此处加了 final 修饰符,有必要吗?为什么
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
懒汉式,在单例对象第一次被使用时构建,
单线程时
public class Singleton {
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
多线程,加锁,但每次都验证锁造成效率问题
public class Singleton {
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
synchronized (Singleton.class) {
if(instance == null){
instance = new Singleton();
}
}
return instance;
}
}
double-check,提升效率
public class Singleton {
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
//double-check
if(instance == null){ //提升效率
synchronized (Singleton.class) { //保证单例
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
但double-check在jdk 1.5 之前某些情况下会发生非预期问题 The "Double-Checked Locking is Broken" Declaration
1.5 及以后版本加上 volatile 修饰可避免非预期问题
public class Singleton {
private volatile static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){
synchronized (Singleton.class) {
if(instance == null){
instance = new Singleton();
}
}
return instance;
}
}
c/c++ 单例实现方式
参考文档
深入浅出单实例Singleton设计模式 by 陈浩