模板方法模式

模板方法模式在开源项目中大量使用

模板方法模式的意思是在abstract类中定义一个公有的行为方法,这个方法是一个模板方法,一般是public final的意味着不可以被子类中的方法重写,里面包含一些完成模板方法需要调用的其他方法,这些方法是protect的,需要在不同的子类中做不同的实现

例如org.springframework.dao.support.DaoSupport类就使用了模板方法

public abstract class DaoSupport implements InitializingBean {

    /** Logger available to subclasses */
    protected final Log logger = LogFactory.getLog(getClass());


   //这个方法就是模板方法,里面包含了两个方法,initDao()和checkDaoConfig()方法,checkDaoConfig()方法需要在

   //不同的子类中做不同的实现,initDao()方法是一个空实现,这种方法被称为钩子方法,作用是占位,可以在子类中重写这个方法

    public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException {
        // Let abstract subclasses check their configuration.
        checkDaoConfig();

        // Let concrete implementations initialize themselves.
        try {
            initDao();
        }
        catch (Exception ex) {
            throw new BeanInitializationException("Initialization of DAO failed", ex);
        }
    }

    /**
     * Abstract subclasses must override this to check their configuration.
     * <p>Implementors should be marked as <code>final</code if concrete subclasses
     * are not supposed to override this template method themselves.
     * @throws IllegalArgumentException in case of illegal configuration
     */
    protected abstract void checkDaoConfig() throws IllegalArgumentException;

    /**
     * Concrete subclasses can override this for custom initialization behavior.
     * Gets called after population of this instance's bean properties.
     * @throws Exception if DAO initialization fails
     * (will be rethrown as a BeanInitializationException)
     * @see org.springframework.beans.factory.BeanInitializationException
     */
    protected void initDao() throws Exception {
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值