设计模式一一一模板方法模式
jdk中的模板方法模式:
/*
* 模板类HttpServlet
*/
public abstract class HttpServlet extends GenericServlet implements java.io.Serializable {
/*
* 模板方法service(),制定逻辑的骨架。逻辑的骨架由多个基本方法构成。基本方法的具体实现由子类来完成。
*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
doGet(req, resp); // 基本方法
} else {
long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp); // 基本方法
} else if (method.equals(METHOD_POST)) {
doPost(req, resp); // 基本方法
} else if (method.equals(METHOD_PUT)) {
doPut(req, resp); // 基本方法
} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp); // 基本方法
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp); // 基本方法
} else if (method.equals(METHOD_TRACE)) {
doTrace(req,resp); // 基本方法
} else {
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}
/*
* 基本方法,具体的实现由子类来完成。
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
}
/*
* 模板的具体实现类
*/
public class MyHttpServlet extends HttpServlet {
/*
* 基本方法的具体实现
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 自定义的处理逻辑
}
}
以上是 设计模式一一一模板方法模式 的全部内容, 来源链接: utcz.com/z/514193.html