首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

转Holder方式

2012-09-28 
转Holder模式原文:http://badqiu.iteye.com/blog/696983??Holder模式的主要功能是将一些Bean可以转为静态

转Holder模式

原文:http://badqiu.iteye.com/blog/696983

?

?

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 ValidatorSpringValidatorHolder用于持有Spring ValidatorApplicationContextHolder用于持有Spring ApplicationContext? CacheHolder用于持有CacheMessagePublisherHodler用于持有类似JMS消息中心的消息发送MessageSourceHolder持用MessageSource?,用于国际化MailerHolder用于邮件发送的MailerConfigHolder用于持有配置,需要动态刷新的参数使用,请查看文章保持类的无状态 SecurityManagerHolder用于权限控制的SecurityManager 1 楼 paulojian 2011-07-12   你的这个问题解决了吗?
    http://www.iteye.com/problems/67646?page=2 2 楼 haohao-xuexi02 2011-07-13   http://www.iteye.com/problems/67646?page=2paulojian 写道你的这个问题解决了吗?
    http://www.iteye.com/problems/67646?page=2
    还没有呢。

热点排行