前言
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;
}