在应用的生存周期中,一个类的实例有且仅有一个
当在一些业务中需要规定某个类的实例有且仅有一个时,就可以用单例模式
比如spring容器默认初始化的实例就是单例的
1、在类中定义私有的静态变量,类型为本类
2、构造器私有化
3、获取单实例的共有静态方法
public class Component {
/**
* 定义私有的静态变量来存放本类的单实例
* 私有保证外部无法直接获取本实例
* 静态保证本实例不会被回收
*/
private static Component component;
private Component(){} //构造器私有化,保证外部无法生成本类的实例,只能在本类中创建实例
/**
* 公共的静态同步方法用来获取本类的单实例
* 保证线程安全(只有一个实例)
* 延迟加载单实例,在第一次调用时才初始化本实例
* @return
*/
public static synchronized Component getInstance(){
if(component == null)
component = new Component();
return component;
}
}
public class Component {
private static Component component = new Component(); //在类加载的时候就初始化本实例
private Component(){} //构造器私有化保证只能在类内部创建本实例
public static Component getInstance(){
return component;
}
}
public class Component {
private static Component component;
private Component(){}
/**
* 双重判断加锁机制
* @return
*/
public static Component getInstance(){
if(component == null){
synchronized (Component.class){
if(component == null)
component = new Component();
}
}
return component;
}
}
在懒加载模式中,每次获取实例都要加锁,这会使程序运行速度变慢,通过双重判断加锁机制可以解决这个问题
方法本身不加锁,进入方法之后先判断实例是否存在,如果存在就直接返回了,这里是多线程的
如果不存在,往下走就加锁变单线程了,但是在进入同步块中还要进行一次判断
关于单例模式这篇博客讲得很好:https://www.cnblogs.com/V1haoge/p/6510196.html