Java design pattern-responsibility chain

Source: Internet
Author: User

Background: To replace the <script> and other <>html tags, to block or replace sensitive words;1. At first it may be written like this:
 Public class Main {    publicstaticvoid  main (string[] args) {        = "Hello everyone:),< Script>, sensitive, employed, Caesar's legitimate thinking environment Flushing sees the reply ";         New msgprocessor ();        Mp.setmsg (msg);         = mp.processor ();        SYSTEM.OUT.PRINTLN (result);}            }
 Public classMsgprocessor {PrivateString msg;  PublicString getmsg () {returnmsg; }     Public voidsetmsg (String msg) { This. msg =msg; }         PublicString Processor () {//process the HTML tag<>String r = msg.replace (' < ', ' ['). Replace (' > ', '] '); //process the sensitive wordsr = R.replace ("Employed", "employment"). Replace ("Sensitive", "" "); returnR; }    }

But the drawbacks of the above:

If there are other logic and other substitutions, then it is necessary to write other substitution laws in the processor, which is not conducive to the expansion;

2. Then change to the following wording:

Define Interface Filter:

 Public Interface Filter {        string doFilter (String str);    }

Class for handling HTML tags:

 Public class Implements Filter {    @Override    public  string doFilter (String str) {        //  Process the HTML tag<>        String r = str.replace (' < ', ' ['). Replace (' > ', '] ');         return R;    }}

Classes that handle sensitive words:

 Public class Implements Filter {    @Override    public  string doFilter (String str) {        //  Process the sensitive words        String    r = str.replace ("Employed", "employment")                       . Replace ("sensitive", "" " );         return R;    }}

Msgprocessor:

 Public classMsgprocessor {PrivateString msg; PrivateFilter[] Filters = {NewHtmlfilter (),Newsensitivefilter ()};  PublicString getmsg () {returnmsg; }     Public voidsetmsg (String msg) { This. msg =msg; }         PublicString Processor () {string R=msg;  for(Filter f:filters) {R=F.dofilter (R); }                returnR; }}

Run the test main and get the result correctly;

The benefits of doing this are:

The newly added rules can be placed in any order of the filters array;

The new filter rules can be arbitrarily extended, as long as the implementation of the filter interface, and implement the method, and then add into the filters array;

But now consider a question:

If there is already a filter chain, you want to add the whole filter chain to the original logic, how to do it?

3. The changes are as follows:

Filterchain.java:

 Public classFilterchainImplementsfilter{List<Filter> filters =NewArraylist<filter>();  PublicFilterchain addfilter (Filter f) { This. Filters.add (f); return  This; }         Publicstring DoFilter (String str) {string R=str;  for(Filter f:filters) {R=F.dofilter (R); }        returnR; }}

Msgprocessor:

 Public classMsgprocessor {PrivateString msg; PrivateFilterchain FC;  PublicString getmsg () {returnmsg; }     Public voidsetmsg (String msg) { This. msg =msg; }     PublicFilterchain getfc () {returnFC; }     Public voidSETFC (Filterchain FC) { This. FC =FC; }         PublicString Processor () {returnFc.dofilter ( This. msg); }}

Main:

 Public classMain { Public Static voidMain (string[] args) {String msg= "everyone good:), <script>, sensitive, employed, Caesar's legitimate thinking environment Flushing sees the reply"; Msgprocessor MP=Newmsgprocessor (); Filterchain FC=NewFilterchain (); //set up the filter rule chain.Fc.addfilter (NewHtmlfilter ()). addfilter (NewFacefilter ()); Filterchain FC2=NewFilterchain (); Fc2.addfilter (NewSensitivefilter ());                Fc.addfilter (FC2);        Mp.setmsg (msg);                MP.SETFC (FC); String result=mp.processor ();            SYSTEM.OUT.PRINTLN (result); }}

Run Main, print:

Hello ^_^, [script], employment, Caesar's legitimate thinking environment flushing see reply

4. Both processing the send to the server and also processing the return from the server to the client:

Now just the message from one to the other end of the filter, and the reality is often the message from the client to the server side, the server also has a feedback, now want to do such a filter, you can filter from the client to the server side of the message, you can also filter from the server side of the message returned; Like Struts2 's interceptor and Tomcat, the filter of the container is doing the same, dealing with both the past and the back, and by handing the request and the response to the filter, which can handle the request object, Can also dispose of the response object;The order of the filters that handle the request and the order in which the filters are processed response exactly the opposite:The simple use of the request contains a string that contains a string in the response to simply simulate:

On the code:

Request:

 Package Com.cy.dp.filter;  Public class Request {    String requeststr;      Public String getrequeststr () {        return  requeststr;    }      Public void setrequeststr (String requeststr) {        this. requeststr = requeststr;    }} 
View Code

Response:

 Package Com.cy.dp.filter;  Public class Response {    String responsestr;      Public String getresponsestr () {        return  responsestr;    }      Public void setresponsestr (String responsestr) {        this. responsestr = responsestr;    }} 
View Code

Filter:

 Package Com.cy.dp.filter;  Public Interface Filter {        void  doFilter (Request request, Response Response, Filterchain chain);    }

Htmlfilter:

 Package Com.cy.dp.filter;  Public class Implements Filter {    @Override    publicvoid  doFilter (Request request, Response Response, Filterchain chain) {        //process the HTML tag<>        request.requeststr = Request.requestStr.replace (' < ', ' ['). Replace (' > ', '] ') + "----htmlfilter ()";        Chain.dofilter (Request, response, chain);                 + = "----Htmlfilter ()";}        }
View Code

Sensitivefilter:

 Package Com.cy.dp.filter;  Public class Implements Filter {    @Override    publicvoid  doFilter (Request request, Response Response, Filterchain chain) {                //process The sensitive words        request.requeststr = Request.requestStr.replace ("Employed", "employment"). Replace ("sensitive", "" ") +"----sensitivefilter () ";        Chain.dofilter (Request, response, chain);                 + = "----Sensitivefilter ()";}    }
View Code

Facefilter:

 Package Com.cy.dp.filter;  Public class Implements Filter {        @Override    publicvoid  doFilter (Request request, Response Response , Filterchain chain) {        //processthe face        request.requeststr = Request.requestStr.replace (":)", "^_^") + "----facefilter ()";        Chain.dofilter (Request, response, chain);                 + = "----Facefilter ()";}    }
View Code

Filterchain:

 PackageCom.cy.dp.filter;Importjava.util.ArrayList;Importjava.util.List; Public classFilterchainImplementsfilter{List<Filter> filters =NewArraylist<filter>(); intindex = 0;  PublicFilterchain addfilter (Filter f) { This. Filters.add (f); return  This; } @Override Public voidDoFilter (Request request, Response Response, Filterchain chain) { If(Index==filters.size ()) return ; Filter F=Filters.get (index); Index++;    F.dofilter (Request, response, chain); }}

Test code main:

 PackageCom.cy.dp.filter; Public classMain { Public Static voidMain (string[] args) {String msg= "everyone good:), <script>, sensitive, employed, Caesar's legitimate thinking environment Flushing sees the reply"; Request Request=NewRequest ();        REQUEST.SETREQUESTSTR (msg); Response Response=NewResponse (); Response.setresponsestr ("Response"); //set up the filter rule chain.Filterchain FC =NewFilterchain (); Fc.addfilter (NewHtmlfilter ()). addfilter (NewSensitivefilter ()). addfilter (NewFacefilter ());                Fc.dofilter (Request, response, FC);        System.out.println (Request.getrequeststr ());    System.out.println (Response.getresponsestr ()); }}

Operation Result:

Hello ^_^, [script], employment, Caesar's legitimate thinking environment flushing see reply----htmlfilter ()----sensitivefilter ()----facefilter () Response--- -facefilter ()----sensitivefilter ()----htmlfilter ()

Java design pattern-responsibility chain

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.