【Java设计模式】:行为型模式—模板模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hxcaifly/article/details/86485102

1.模板模式的定义

定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。 模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。通俗的说的就是有很多相同的步骤的,在某一些地方可能有一些差别适合于这种模式,如大话设计模式中说到的考试场景中,每个人的试卷都是一样的,只有答案不一样。这种场景就适合于模板方法模式。我这次自己写的是一个汽车启动的过程,每一种汽车启动的过程都基本是一样的流程,无非是这一过程中存在一些细小差别。

2.模板方法模式UML图

在这里插入图片描述

3.模板方法模式代码

package com.roc.template;
/**
 * 汽车模型
 * 模型模式
 * @author liaowp
 *
 */
public abstract class CarModel {
     /**
      * 汽车启动
      */
     protected abstract void start();
    
     /**
      * 停车
      */
     protected abstract void stop();
     
     /**
      * 用户并不需要关注你的车怎么启动或者停下来的,可以开可以停就可以啦
      */
     final public void excet(){
         this.start();
         this.stop();
     }
}
package com.roc.template;
/**
 * 大众车
 * @author liaowp
 *
 */
public class Wcar extends CarModel{

    @Override
    protected void start() {
        System.out.println("大众车启动 。。。。。。。。突突突");
    }

    @Override
    protected void stop() {
        System.out.println("大众车停车。。。。。。。。。");
    }
}
package com.roc.template;

public class Ocar extends CarModel{

    @Override
    protected void start() {
        System.out.println("奥迪无匙启动。。。。。。。突突突");
    }

    @Override
    protected void stop() {
        System.out.println("奥迪停车。。。。。。。");
    }
}
package com.roc.template;
/**
 * 客户端
 * @author liaowp
 *
 */
public class Client {
    public static void main(String[] args) {
        CarModel wcar=new Wcar();//家里的第一辆车,作为用户的我们并不需要关注车怎么启动的.子类变量变为父类。多态
        wcar.excet();
        
        //突然家里需要第二辆车了   奥迪     我们也不需要关注他怎么生产启动的    
        CarModel ocar=new Ocar();
        ocar.excet();
    }
}

4. 模板方法模式在Servlet中的应用

使用过Servlet的人都清楚,除了要在web.xml做相应的配置外,还需继承一个叫HttpServlet的抽象类。HttpService类提供了一个service()方法,这个方法调用七个do方法中的一个或几个,完成对客户端调用的响应。这些do方法需要由HttpServlet的具体子类提供,因此这是典型的模板方法模式。下面是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) {
                // servlet doesn't support if-modified-since, no reason
                // to go through further expensive logic
                doGet(req, resp);
            } else {
                long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                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 less
                    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 {
            //
            // 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);
        }
    }

当然,这个service()方法也可以被子类置换掉。

下面给出一个简单的Servlet例子:
在这里插入图片描述

从上面的类图可以看出,TestServlet类是HttpServlet类的子类,并且置换掉了父类的两个方法:doGet()和doPost()。

public class TestServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        System.out.println("using the GET method");

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            
        System.out.println("using the POST method");
    }

}

从上面的例子可以看出这是一个典型的模板方法模式。

HttpServlet担任抽象模板角色

模板方法:由service()方法担任。

基本方法:由doPost()、doGet()等方法担任。

TestServlet担任具体模板角色

TestServlet置换掉了父类HttpServlet中七个基本方法中的其中两个,分别是doGet()和doPost()。

5. 模板方法模式适用场景

  1. 在多个子类中拥有相同的方法,而且逻辑相同时,可以将这些方法抽出来放到一个模板抽象类中。
  2. 程序主框架相同,细节不同的情况下,也可以使用模板方法。

猜你喜欢

转载自blog.csdn.net/hxcaifly/article/details/86485102