Holder模式
(本方法屬于作者經驗總結出該模式)
Holder模式的主要功能是將一些Bean可以轉為靜態方法調用.方便使用.
適用于一些系統只存在單例(singleton)并且 十分常用 的基礎服務對象.這些基礎服務如果每次使用spring注入,只會增加無謂的代碼及一些不確定性.
示例如下:
BeanValidatorHolder.validate(bean) // HibernateValidator一般系統只有一個 CacheHolder.get("key") //如Memcached,應用系統也只有一個對象 ApplicationContextHolder.getBean("userInfoService");
與singleton相比特點
- 一個Holder只能持有一個對象
- Holder一般是持有接口,所以你可以方便的改變實現
- 配合spring完成Holder初始化
示例1.CacheHolder?
用于持有Cache對象
1.1在spring中初始化
<bean class="cn.org.rapid_framework.util.holder.CacheHolder"> <property name="cache" ref="memcacheCacheImpl"/> </bean>
1.2使用 CacheHolder?使用
CacheHolder.add("key","cache_value","1h"); //do something
1.3實現
public class CacheHolder implements InitializingBean{ private static Cache cache;
public void afterPropertiesSet() throws Exception { if(cache == null) throw new IllegalStateException("not found 'cache' for CacheHolder "); } public void setCache(Cache c) { if(cache != null) throw new IllegalStateException("CacheHolder already holded 'cache'"); cache = c; }
public static Cache getCache(){ return cache; }
//省略了其它N多cache靜態方法 public static void add(String key, Object value, String expiration) { cache.add(key, value, parseDuration(expiration)); }
public static void cleanHolder() { cache = null; } }
其它可以存在的Holder
holder | 功能 |
BeanValidatorHolder | 用于持有Hibernate Validator |
SpringValidatorHolder | 用于持有Spring Validator |
ApplicationContextHolder | 用于持有Spring ApplicationContext? |
CacheHolder | 用于持有Cache |
MessagePublisherHodler | 用于持有類似JMS消息中心的消息發送 |
MessageSourceHolder | 持用MessageSource?,用于國際化 |
MailerHolder | 用于郵件發送的Mailer |
ConfigHolder | 用于持有配置,需要動態刷新的參數使用,請查看文章保持類的無狀態 |
SecurityManagerHolder | 用于權限控制的SecurityManager |