单例设计的核心本质在于:类内部的构造方法私有化,在类的内部产生类的实例化对象通过static方法获取实例化对象。单例设计模式一共有两类:懒汉式、饿汉式。
本节主要讨论懒汉式。
范例:观察懒汉式单例的问题
package reflect;
public class Demo{
public static void main(String[] args) {
for(int x = 0;x < 3;x++){
new Thread(()->{
Singleton.getInstance().print();
},"线程"+x).start();
}
}
}
class Singleton{
private static Singleton instance = null;
//私有化构造,确保只有一个实例。
private Singleton(){
System.out.println("【"+Thread.currentThread().getName()+"】产生了实例");
}
//如果没有实例则创建一个并返回
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
public void print(){
System.out.println("【懒汉式单例设计】");
}
}
【线程0】产生了实例
【懒汉式单例设计】
【线程1】产生了实例
【懒汉式单例设计】
【线程2】产生了实例
【懒汉式单例设计】
单例设计的运行过程之中只允许差生一个实例化对象,这个时候会发现当有了若干线程之后,实际上当前程序就可以产生多个实例化对象,那么此时就不是单例设计模式了。
此时造成问题的关键在于代码本身出现了不同步的情况,而要想解决问的关键和新在于需要进行同步处理,同步自然能想到synchronized关键字。
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
这个时候的确是进行了同步处理,但是这个同步的代价是效率急剧降低(一次只能有一个线程进去)。在代码中其实只有一块代码需要同步处理(instance对象的实例化处理部分),再这样的情况下同步加载并不合适。
范例:更加合理的同步处理
public static Singleton getInstance(){
if(instance == null){ //此时任然有线程同时进入
synchronized (Singleton.class) { //线程同步
//再次判断,只能有一个线程进去,而后实例化对象,再次进来时多个线程将执行完if后直接返回对象
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
完整代码:
package reflect;
public class Demo{
public static void main(String[] args) {
for(int x = 0;x < 3;x++){
new Thread(()->{
Singleton.getInstance().print();
},"线程"+x).start();
}
}
}
class Singleton{
private static volatile Singleton instance = null; //直接操作原数据不生成副本
//私有化构造,确保只有一个实例。
private Singleton(){
System.out.println("【"+Thread.currentThread().getName()+"】产生了实例");
}
//如果没有实例则创建一个并返回
public static Singleton getInstance(){
if(instance == null){ //此时任然有线程同时进入
synchronized (Singleton.class) { //线程同步
//再次判断,只能有一个线程进去,而后实例化对象,再次进来时多个线程将执行完if后直接返回对象
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
public void print(){
System.out.println("【懒汉式单例设计】");
}
}
面试题:实现一个单例设计
- 【100%】字节编写一个饿汉式的单例设计模式,并且实现构造方法私有化;
- 【120%】在Java中哪里使用到了单例设计模式?Runtime、Pattern、Spring;
- 【200%】懒汉式单例设计模式的问题?