【设计模式】之单例模式

发布于:2024-05-03 ⋅ 阅读:(21) ⋅ 点赞:(0)

系列文章目录


文章目录

今天给大家介绍23种设计模式中的单例模式,也是大家比较常见的一种设计模式,但是,里面的一些细节还是有很多人会忽略的。🌈


一、什么是单例模式

单例模式是指在内存中只会创建且仅创建一次对象的设计模式。在程序中多次使用同一个对象且作用相同时,为了防止频繁地创建对象使得内存飙升,单例模式可以让程序仅在内存中创建一个对象,让所有需要调用的地方都共享这一单例对象。

二、如何使用单例模式

1.单线程使用

这种方式只适合单线程下使用,多线程下会实例化多个对象,不一定是10个。

public class Single {
    private static Single instance;

    private Single(){
        System.out.println("实例化Single对象");
    }
    public static Single getInstance(){
        if (instance == null) instance = new Single();
        return instance;
    }
}

测试:

public class test {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Single.getInstance();
        }
    }
}
测试结果:
    /*
    实例化Single对象
    Process finished with exit code 0
    */

2.多线程使用(一)

只需添加一个synchronized 关键字即可

public class Single {
    private static Single instance;

    private Single(){
        System.out.println("实例化Single对象");
    }
    public synchronized static Single getInstance(){
        if (instance == null) instance = new Single();
        return instance;
    }
}

测试:

public class test {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                Single.getInstance();
            }).start();
        }
    }
}
测试结果:
    /*
    实例化Single对象

    Process finished with exit code 0

    */
虽然添加 synchronized 可以在多线程下保证实例化一次对象,但是因为加锁,会造成系统资源浪费。假设我们遍历10次,相当经过多次经过锁,而我们只需要保证第一次实例化成功,也就是加一次锁,后面的会经过逻辑判断,不会实例化对象。因此,我们引出了下面一种方法。

3.多线程使用(二)

在类加载的时候直接实例化对象。

public class Single {
    private static Single instance = new Single();

    private Single(){
        System.out.println("实例化Single对象");
    }
    public  static Single getInstance(){
        return instance;
    }
}

测试结果跟上方一样

4.多线程使用(三)双重检测

这种方式也能大大减少锁带来的性能消耗。

public class Single {
    private volatile static Single instance ;

    private Single(){
        System.out.println("实例化Single对象");
    }
    public static Single getInstance(){
        if (instance == null){
            synchronized (Single.class){
                if (instance == null){
                    instance = new Single();
                }
            }
        }
        return instance;
    }
}

总结

以上就是单例模式在单多线程下的使用以及优化,今天就先介绍到这里,我们下期再见。✋


网站公告

今日签到

点亮在社区的每一天
去签到