模板方法模式在开源项目中大量使用
模板方法模式的意思是在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 {
}
}