侧边栏壁纸
博主头像
惊羽博主等级

hi ,我是惊羽,前生物学逃兵,现系统工程沉迷者 . 贝壳签约工程师 , 曾被雇佣为 联拓数科 · 支付研发工程师 、京东 · 京东数科 · 研发工程师、中国移动 · 雄安产业研究院 · 业务中台技术负责人 .

  • 累计撰写 102 篇文章
  • 累计创建 14 个标签
  • 累计收到 14 条评论

设计模式(4) -单例模式

惊羽
2021-06-18 / 0 评论 / 0 点赞 / 141 阅读 / 1,455 字
温馨提示:
本文为原创作品,感谢您喜欢~

当实例的应用场景是单例,并且创建和销毁的开销比较大,长时间应用的实例,考虑用单例模式;

① spring依赖注入时,其注入实例都是单例的

源码 :

    
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            synchronized (this.singletonObjects) {
                singletonObject = this.earlySingletonObjects.get(beanName);
                if (singletonObject == null && allowEarlyReference) {
                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                    if (singletonFactory != null) {
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return (singletonObject != NULL_OBJECT ? singletonObject : null);
    }

先从缓存获取bean(this.singletonObjects.get(beanName)),如为null,则单例加锁构造一个实例,保证注入的实例都是单例的,这些实例都是不太容易销毁的,所以这样做节省了重复创建对象的开销;

② 例如jdbc中,DriverManager,其本身是一个管理者角色,用于统筹 Driver的register和获取Connection的衔接,更偏向于面向过程,其根本就没有实例化的必要,所以可以用私有化其构造方法来控制;

源码 :

package java.sql;

....
public class DriverManager {
	....
  /* Prevent the DriverManager class from being instantiated. */
    private DriverManager(){}
	....
}
0
广告 广告

评论区