日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

模板方法源码解析(jdk+servlet+mybatis)

發布時間:2024/4/13 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 模板方法源码解析(jdk+servlet+mybatis) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
模板方法在JDK中的一些應用,AbstractList這么一個抽象類,public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>我們看一下他的實現,就知道這個類是做什么的,可以看到在很多開源包中,都實現了這個類,那他肯定是為了擴展,自己List這個數據結構的,然后JDK中ArrayList,你們應該都很熟悉,那在這個類里邊,有一個addAll方法,包括其他方法也是類似的,/*** {@inheritDoc}** <p>This implementation gets an iterator over the specified collection* and iterates over it, inserting the elements obtained from the* iterator into this list at the appropriate position, one at a time,* using {@code add(int, E)}.* Many implementations will override this method for efficiency.** <p>Note that this implementation throws an* {@code UnsupportedOperationException} unless* {@link #add(int, Object) add(int, E)} is overridden.** @throws UnsupportedOperationException {@inheritDoc}* @throws ClassCastException {@inheritDoc}* @throws NullPointerException {@inheritDoc}* @throws IllegalArgumentException {@inheritDoc}* @throws IndexOutOfBoundsException {@inheritDoc}*/ public boolean addAll(int index, Collection<? extends E> c) {rangeCheckForAdd(index);boolean modified = false;for (E e : c) {add(index++, e);modified = true;}return modified; }我們先選擇一個來看,例如說addAll,這里就可以理解成他呢是對外開放的一個方法,這里面的具體實現呢,就可以理解成addAll這個算法里面的具體順序,以及步驟,那對于很多List的實現呢,他們get獲取具體元素的實現呢,是不一樣的,那我們看一下get這個方法/*** {@inheritDoc}** @throws IndexOutOfBoundsException {@inheritDoc}*/ abstract public E get(int index);可以看到他是abstract方法,是一個抽象的方法,完全交由子類來實現,我們來看一下ArrayList里面的get/*** Returns the element at the specified position in this list.** @param index index of the element to return* @return the element at the specified position in this list* @throws IndexOutOfBoundsException {@inheritDoc}*/ public E get(int index) {rangeCheck(index);return elementData(index); }這里面實現了他的父類AbstractList里面的get方法,里面有兩個步驟,首先進行范圍的一個check,然后通過這個索引,返回具體的elementData,其他也是同理,那對于這個抽象List,當然會有抽象Set,public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E>那既然有抽象Set,那就會有抽象Mappublic abstract class AbstractMap<K,V> implements Map<K,V>他們三個都是同理,里面定義一套算法模板,該開放的開放,該自己實現的自己來實現,然后我們再看一下模板方法在servlet里面的實現,這個類相信你們都非常的熟悉,HttpServlet,他在這個類里面有幾個非常重要的方法,比如我們經常使用的doGet,public abstract class HttpServlet extends GenericServletprotected 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);} }還有doPost,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);} }protected這么一個權限的方法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) {// servlet doesn't support if-modified-since, no reason// to go through further expensive logicdoGet(req, resp);} else {long ifModifiedSince;try {ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);} catch (IllegalArgumentException iae) {// Invalid date header - proceed as if none was setifModifiedSince = -1;}if (ifModifiedSince < (lastModified / 1000 * 1000)) {// If the servlet mod time is later, call doGet()// Round down to the nearest second for a proper compare// A ifModifiedSince of -1 will always be lessmaybeSetLastModified(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 {//// Note that this means NO servlet supports whatever// method was requested, anywhere on this server.//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);}}這個類就定義了一個處理模板,我們平時使用的時候,只要繼承這個Servlet,并且實現doGet,doPost,這兩個方法就可以了,當然還有do其他類型的,那在SpringMVC數據綁定中,你們可以學習一下,那些也是有講的,在RestFul這個章節,也就是這個類定義了一套模板,子類可以來重寫doGet,或者doPost,或者doXxx這么一個方法,按這個也是模板設計模式在servlet中的一些應用,那在Mybatis當中,當然也有對應的應用,看一下BaseExecutor這么一個類public abstract class BaseExecutor implements Executor回到最上邊我們看一下,首先這個類是抽象類,翻譯過來就是一個基礎的執行人,實現了執行人接口,我們看一下這里面的方法,這里面的方法有很多,他實現了大部分的SQL執行邏輯,然后把幾個方法交給子類來定制化執行,我們看一下doUpdate這個方法protected abstract int doUpdate(MappedStatement ms, Object parameter)throws SQLException;還有doFlush,doQuery,doQueryCursorprotected abstract List<BatchResult> doFlushStatements(boolean isRollback)throws SQLException;protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql)throws SQLException;protected abstract <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds, BoundSql boundSql)throws SQLException;這四個方法完全是抽象方法,交由子類來實現,那么這個類都有哪些子類呢,我們來看一下,一共有這四個子類,簡單的,close的,Batch,reuse

我們隨便看一個,比如doUpdate,這四個子類中都有具體的實現,比如Simple里面的@Override public int doUpdate(MappedStatement ms, Object parameter) throws SQLException { Statement stmt = null; try {Configuration configuration = ms.getConfiguration();StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);stmt = prepareStatement(handler, ms.getStatementLog());return handler.update(stmt); } finally {closeStatement(stmt); } }Executor這個類有四個實現類,分別對應不同的業務場景,比如剛剛說的Batch,這個是對應批量Update來使用的public class BatchExecutor extends BaseExecutor從名字就能看出來,而Reuse就是重用的public class ReuseExecutor extends BaseExecutorSimple就是簡單的/*** @author Clinton Begin*/ public class SimpleExecutor extends BaseExecutor 那我們看一下簡單的doUpdate是怎么實現的呢,只所以定義為SimpleExecutor呢,是因為這里的實現足夠簡單,例如每執行一次Update的時候,這里就new了一個newStatementHandler,@Override public int doUpdate(MappedStatement ms, Object parameter) throws SQLException { Statement stmt = null; try {Configuration configuration = ms.getConfiguration();StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);stmt = prepareStatement(handler, ms.getStatementLog());return handler.update(stmt); } finally {closeStatement(stmt); } }后面是具體的各種參數,每執行一次就new一個newStatementHandler,然后通過handler來生成一個statement,然后執行update,執行完成之后,在finally里面進行關閉,而BatchExecutor里邊呢/*** @author Jeff Butler */ public class BatchExecutor extends BaseExecutor 考慮的批量執行update語句,有興趣的可以仔細來閱讀以下@Overridepublic int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {final Configuration configuration = ms.getConfiguration();final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);final BoundSql boundSql = handler.getBoundSql();final String sql = boundSql.getSql();final Statement stmt;if (sql.equals(currentSql) && ms.equals(currentStatement)) {int last = statementList.size() - 1;stmt = statementList.get(last);applyTransactionTimeout(stmt);handler.parameterize(stmt);//fix Issues 322BatchResult batchResult = batchResultList.get(last);batchResult.addParameterObject(parameterObject);} else {Connection connection = getConnection(ms.getStatementLog());stmt = handler.prepare(connection, transaction.getTimeout());handler.parameterize(stmt); //fix Issues 322currentSql = sql;currentStatement = ms;statementList.add(stmt);batchResultList.add(new BatchResult(ms, sql, parameterObject));}// handler.parameterize(stmt);handler.batch(stmt);return BATCH_UPDATE_RETURN_VALUE;}那這些都是模板方法設計模式在JDK,Servlet,以及Mybatis中的一些應用,模板方法這個設計模式,比較簡單,相信通過這里的學習,是非常容易理解,模板方法設計模式的,同時我們在定制的時候,也注意一下,特意設置的設計模式課程,和前端課程,這兩個不是一個level的,這種實體類,那里面也有一些注意的點,希望你們對于模板方法設計模式呢,能理解透,用好

?

總結

以上是生活随笔為你收集整理的模板方法源码解析(jdk+servlet+mybatis)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。