GOF给模板方法(Template Method)模式定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。这里的算 法的结构,可以理解为你根据需求设计出来的业务流程。特定的步骤就是指那些可能在内容上存在变数的环节。
可以看出来,模板方法模式也是为了巧妙解决变化对系统带来的影响而设计的。使用模板方法使系统扩展性增强,最小化了变化对系统的影响。这一点,在下面的举例中可以很明显的看出来。
来看下这个简单模式的结构吧:
1) AbstractClass(抽象类):定义了一到多个的抽象方法,以供具体的子类来实现它们;而且还要实现一个模板方法,来定义一个算法的骨架。该模板方法不仅调用前面的抽象方法,也可以调用其他的操作,只要能完成自身的使命。
2) ConcreteClass(具体类):实现父类中的抽象方法以完成算法中与特定子类相关的步骤。
最近项目中网页超时判断、权限控制等功能,使用模板方法模式在控制层实现,颇有借鉴意义。
public abstract class BaseAction extends Action {
private static Logger logger = Logger.getLogger(BaseAction.class);
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
logger.info("now enter BaseAction:execute method!");
HttpSession session = request.getSession(false);
ActionErrors errors = new ActionErrors();
logger.info("session:" + session);
// 网页超时
if (session == null) {
logger.error("session has been timeout!");
request.setAttribute("message", "网页超时,请重新登录!");
return mapping.findForward("session_time_out");
} else {
if ((OperatorInfoView) session.getAttribute("operator") == null) {
logger.info(" OperatorInfoView is null");
request.setAttribute("message", "网页超时,请重新登录!");
return mapping.findForward("session_time_out");
}
}
// 权限
Boolean flag = Boolean.FALSE;
String authorityKey = this.getAuthorityId();
flag = this.getPrivilege(session, authorityKey);
if (!flag.booleanValue()) {
request.setAttribute("message", "对不起,您没有权限!");
return mapping.findForward("error");
}
logger.info("BaseAction execute method operated successfully!");
return execute(mapping, form, request, response, errors, session);
}
public abstract ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response, ActionErrors errors,
HttpSession session);
/**
* 获得权限
*/
public abstract String getAuthorityId();
protected Boolean getPrivilege(HttpSession session, String authorityKey) {
Boolean flag = Boolean.FALSE;
List authorityList = (List) session.getAttribute("authorityList");
if (authorityList != null) {
...
flag = Boolean.TRUE;
}
return flag;
}
//打印错误信息
public void messageError(HttpServletRequest request, String msg) {
ActionMessages actionMessages = new ActionMessages();
actionMessages.add(Constant.ERROR, new ActionMessage(msg));
addMessages(request, actionMessages);
}
}
public class PreAddPersonAction extends BaseAction {
private static final Logger logger = Logger.getLogger(PreAddPersonAction.class);
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response,
ActionErrors errors, HttpSession session) {
messageError(request, "资源文件信息");
return mapping.findForward("success");
}
@Override
public String getAuthorityId() {
return 常量;
}
}