Responsibility chain design mode (filter, Interceptor) _ Design mode

Source: Internet
Author: User
Tags java web

The application of the responsibility chain design pattern (Chain of responsibility) is: the filter chain in the Java web, and the interceptor stack in the Struts2.

Let's look at one question:

Given a string "employed:", sensitive information is,<script>, the HTML tags and sensitive words are filtered or replaced.
This paper mainly explains the design pattern of responsibility chain by the evolution of the design method of this problem.

First design: no design pattern

A Msgprocessor class was designed to accomplish the main task of string processing. The MainClass class is the test class in this design.

public class MainClass {public
    static void Main (string[] args) {
        //Required filtered statement
        String msg = "employed:), sensitive information, <SC Ript> ";
        Instantiate processing class
        Msgprocessor MP = new Msgprocessor (msg);
        String r = mp.process ();
        System.out.println (R);
    }
public class Msgprocessor {
    private String msg;
    Public msgprocessor (String msg) {
        this.msg = msg;
    }
    public string process () {
        string r = msg;
        Filter the HTML tags in msg
        r = r.replace ("<", "<"). Replace (">", ">");
        Filter sensitive word
        r = r.replace ("Sensitive", ""). Replace ("employed", "employment");
       return r;
    }
}

Second design: Add a filter interface

In the first design, all processing of a string is placed in the Msgprocessor class with very poor extensibility. If you want to filter the smiley face in the string (replace ":)" with "^_^", you need to change the process method in Msgprocessor.

Public interface Filter {
    string dofilter (String str);
}
public class Htmlfilter implements Filter {public
    string Dofilter (String msg) {
        string r = msg;
        Filter the HTML tags in msg
        r = r.replace ("<", "<"). Replace (">", ">");
       return r;
    }
}
 
public class Sensitivefilter implements Filter {public
    string Dofilter (String msg) {
        string r = msg;
        Filter sensitive word
        r = r.replace ("Sensitive", ""). Replace ("employed", "employment");
        return r;
    }
}
 
public class Msgprocessor {
    private String msg;
    Private filter[] Filters = {new Htmlfilter (), New Sensitivefilter ()};
    Public msgprocessor (String msg) {
        this.msg = msg;
    }
    public string process () {
        string r = msg;
        for (Filter f:filters) {
            R = f.dofilter (r);
        }
        return r;
    }
}

At this point, if you need to filter the smiley face in the string, simply create a class Facefilter implement the filter interface and enlist in the Filters field in the Msgprocessor class.

The third design: Responsibility chain model (Filterchain)

Definition: Assign an event-handling process to a set of executing objects that form a chain structure in which event-handling requests are passed on this set of execution objects. The main participation role of the responsibility chain model:

① Event Handling Request object (Request)

② Execution Object (Handler)


public class Filterchain implements Filter {public list<filter> filters= new arraylist<filter> ();
        Public Filterchain addfilter (Filter f) {filters.add (f);
    return this;
        public string Dofilter (String msg) {//executing the Dofilter method in filters can be string r = Msg;
        for (Filter f:filters) {r = F.dofilter (r);
    } return R;
    } public class Msgprocessor {private String msg;
    Private Filterchain chain = new Filterchain ();
        Public Msgprocessor (String msg,filter Chain) {this.msg = msg;
    This.chain = chain;
    Public String process () {return chain.dofilter (msg); } public class MainClass {public static void main (string[] args) {//Required filtered statement String msg = "was employed:),
        Sensitive information,<script> ";
        Get a cross filter chain filterchain chain = new Filterchain ();
        Chain.addfilter (New Htmlfilter ()). addfilter (New Sensitivefilter ()); Instantiation Processing Class MsgprocessOr MP = new Msgprocessor (msg,chain);
        String r = mp.process ();
    System.out.println (R); }
}

Responsibility chain Mode Enhanced Edition
The filter chain for the above implementation can be expressed in figure a below, and the whole process is filtered only once for MSG. and the process of executing the filter chain in Javaweb and the interceptor stack in STRUTS2 can be represented as graph b,☆ very important.

The following program simulates the filter in Javaweb to implement a filter similar to request and response. The main involved classes are as follows:

public interface Filter {void Dofilter (Request req,response resp,filterchain chain); \ public class Htmlfilter Implem
        Ents filter {public void Dofilter (Request req, Response resp, filterchain chain) {//filter HTML tags in req.reqstr
        Req.reqstr = Req.reqStr.replace ("<", "<"). Replace (">", ">");
        Req.reqstr + = "---htmlfilter ()---";
        Chain.dofilter (req, resp);
    Resp.respstr + = "---htmlfilter ()---"; } public class Sensitivefilter implements Filter {public void Dofilter (Request req, Response resp, Filterchain Chai
        N) {//filter req.reqstr the sensitive word req.reqstr = Req.reqStr.replace ("Sensitive", ""). Replace ("employed", "employment");
        Req.reqstr + = "===sensitivefilter";
        Chain.dofilter (req, resp);
    Resp.respstr + = "===sensitivefilter";
    } public class filterchain{private list<filter> filters = new arraylist<filter> ();
    When calling the filter on the chain, record the position of the filter with private int index = 0; Public Filterchain addfilter (FiltEr f) {filters.add (f);
    return this;
        public void Dofilter (Request req, Response resp) {if (index = = filters.size ()) return;
        Gets the current filter filter F = filters.get (index);
        index++;
    F.dofilter (req, resp, this);
The public class Request {//Only maintains one REQSTR field record for request in the request//For convenience of simulation, the REQSTR is not set to private String reqstr; The public class Response {//Response only one respstr field record for Response Operations//For convenience of simulation, the RESPSTR is not set to private String res
PSTR;
} package Org.flyne.fiter; public class MainClass {public static void main (string[] args) {//Required filtered statement String msg = "employed:), sensitive letter
        Interest,<script> ";
        Create request, Response object Request req = new request ();
        Response resp = new Response ();
        REQ.REQSTR = msg;
        RESP.RESPSTR = "Response";
        Engage a filter chain with two filters on the chain filterchain chain = new Filterchain (); Chain.addfilter (New Htmlfilter ()). addfilter (New Sensitivefilter ());
        Start filtering Chain.dofilter (req, resp);
        System.out.println (REQ.REQSTR);
    System.out.println (RESP.RESPSTR); }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.