独一无二的对象。

    和全局变量有什么区别?

    全局变量:程序一开始就创建好对象,对象可能非常消耗资源,而程序在这次执行构成中一次也没有使用。

    我们来看一下最简单的一个单例模式

    1. public class Singleton {
    2. private static Singleton uniqueInstance;
    3. private Singleton() {}
    4. public static Singleton getInstance() {
    5. if (uniqueInstance == null) {
    6. uniqueInstance = new Singleton();
    7. }
    8. return uniqueInstance;
    9. }
    10. }


    如果要处理多线程怎么办? 、加入synchronized关键字

    1. public class Singleton {
    2. private static Singleton uniqueInstance;
    3. private Singleton() {}
    4. public static synchronized Singleton getInstance() {
    5. if (uniqueInstance == null) {
    6. uniqueInstance = new Singleton();
    7. }
    8. return uniqueInstance;
    9. }
    10. }

    我们想一下,这样子会有什么问题:

    • 每次获取这个实例都需要同步
    • 其实在uniqueInstance初始化后,就不需要同步了

    改进一下:
    第一种(静态初始化):

    1. public class Singleton {
    2. private static Singleton uniqueInstance = new Singleton();
    3. private Singleton() {}
    4. public static synchronized Singleton getInstance() {
    5. return uniqueInstance;
    6. }
    7. }

    第二种(双重检查加锁):

    1. public class Singleton {
    2. private volatile static Singleton uniqueInstance = new Singleton();
    3. private Singleton() {}
    4. public static synchronized Singleton getInstance() {
    5. if (uniqueInstance == null) {
    6. synchronized (Singleton.class) {
    7. if (uniqueInstance == null) {
    8. uniqueInstance = new Singleton();
    9. }
    10. }
    11. }
    12. return uniqueInstance;
    13. }
    14. }

    注意:volatile关键字的作用