tomcat8 源码 之单例模式

前言

tomcat8源码中应用了很多设计模式,通过探究源码,get到了这些优秀的设计模式如何在成熟的软件产品中被淋漓尽致的使用,下面先聊聊当中的单例模式

1、背景概述

**
tomcat中有一套完善的异常信息管理机制,在每个需要异常管理的工程包下都有相应的 properties 文件,文件中主要定义了各自pacakage下的类的各种异常信息,极大的方便了对异常信息的维护
这里写图片描述
这里写图片描述
其中,采用org.apache.tomcat.util.res.StringManager来完成对信息的操作,考虑到异常信息的频繁操作,为避免浪费内存资源,避免创建过多的StringManager实例,该类对象用单例模式创建
看下作者对该类的描述:
这里写图片描述

2、StringManager源码学习

public class StringManager {
   

   // **Locale的缓存个数**
   private static int LOCALE_CACHE_SIZE = 10;

    /**java.util.ResourceBundle 用于读取properties文件
     * The ResourceBundle for this StringManager.
     */
    private final ResourceBundle bundle;

    //一个 Locale对象代表一个特定的地理、政治或文化区
    private final Locale locale;


    /**
     * 私有的构造函数
     * 传入包名和Locale 
     */
    private StringManager(String packageName, Locale locale) {
        String bundleName = packageName + ".LocalStrings";
        ResourceBundle bnd = null;
        try {
            bnd = ResourceBundle.getBundle(bundleName, locale);
        } catch (MissingResourceException ex) {
            // Try from the current loader (that's the case for trusted apps)
            // Should only be required if using a TC5 style classloader structure
            // where common != shared != server
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            if (cl != null) {
                try {
                    bnd = ResourceBundle.getBundle(bundleName, locale, cl);
                } catch (MissingResourceException ex2) {
                    // Ignore
                }
            }
        }
        bundle = bnd;
        //获取实际的语言环境,这可能与所请求的语言环境不同
        // Get the actual locale, which may be different from the requested one
        if (bundle != null) {
            Locale bundleLocale = bundle.getLocale();
            if (bundleLocale.equals(Locale.ROOT)) {
                this.locale = Locale.ENGLISH;
            } 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值