《Head First设计模式》之单例模式

​​​​单例模式定义:
这里写图片描述

普通单例代码实现:

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

        /* 需要将无参构造函数私有化,防止应用通过默认 new 的方式初始化实例*/
        private Singleton() {

        public static Singleton getInstance() {
        return instance;
        }
    }

通常会使用懒加载模式,即使用的时候才进行实例化:


public class Singleton {
        private static Singleton instance;

        private Singleton() {
        }

        public static Singleton getInstance() {
            if (instance == null) {
            instance = new Singleton();
            }
        return instance;
        }
    }

如果有多线程操作的情况下,就可以在if (instance == null)环节出现问题,因为多个线程获取实例,同时调用该方法可能new出两个不同的实例。


解决方法:

①、不使用懒加载的机制(缺点:即时不实用该实例也进行了初始化,耗存)
②、利用synchronized进行同步。
这里写图片描述

缺点:每次都进行同步,大大降低了系统的性能)

③、最优方案:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_33404395/article/details/81285248