Java设计模式:责任链

上一篇 / 下一篇  2012-10-10 13:59:09 / 个人分类:Java

N%A(@+yU^'t0  责任链模式(Chain of Responsibility)的目标是使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。

1OeoB)~5|X I0

mZ){;bF~0  在处理用户的请求时可能要根据不同的情况对请求添加不同的处理逻辑,在这时候就可以利用责任链进行设计。当需要添加一个处理逻辑时可以很方便的添加一个处理的节点。

p7I z)mC6K b%X2T051Testing软件测试网g Ne)tfe

  现在我们的需求是处理用户的请求,将用户提交的字符串信息进行层层处理,同时在处理完成之后返回结果时,也要对返回的字符串进行层层处理,而处理返回的情况时其处理的顺序和先前是正好相反的顺序。51Testing软件测试网`*\r-YT)Y#_LP ^

51Testing软件测试网f.Bg|(h"S }

  首先建立用户的请求和接收对象Request和Response:51Testing软件测试网5y4Y#Pjnd8js

  1. packagecom.lcq.filter;
  2. 51Testing软件测试网O}pRw#^jmk
  3. publicclassRequest {
  4. String requestStr;

  5. 'X#]%bAU!p{0
  6. publicString getRequestStr() {
  7. returnrequestStr;
  8. }
  9. 51Testing软件测试网.abbj,R%v${8M
  10. publicvoidsetRequestStr(String requestStr) {
  11. this.requestStr = requestStr;
  12. }

  13. S~~q0}!z j9}]G0
  14. }
  1. packagecom.lcq.filter;

  2. )m&`*h y+z0
  3. publicclassResponse {
  4. String responseStr;

  5. J1h+N!aUM&D0
  6. publicString getResponseStr() {
  7. returnresponseStr;
  8. }

  9. j ~6m,T(D g0
  10. publicvoidsetResponseStr(String responseStr) {
  11. this.responseStr = responseStr;
  12. }
  13. 51Testing软件测试网0OP~9I|5x*K O
  14. }

2k(pY7S Q$ve3O0  我们将处理用户信息的逻辑抽象成为一个个的过滤器,进一步抽象出过滤器接口Filter:

!X'{2Spk%Y)g0
  1. packagecom.lcq.filter; 
  2. 51Testing软件测试网3G)a5b/i~A9Nv+s
  3. publicinterfaceFilter { 
  4.    publicvoiddoFilter(Request request, Response response,FilterChain chain); 

  5. 9l9|.@)sf(A0
  6. }

8Y#f8h;W.H0  注意在Filte接口中doFilter方法参数中有FilterChain的一个变量,我们再建立FilterChain类:51Testing软件测试网7{|*S,R/`5J

  1. packagecom.lcq.filter; 
  2. 51Testing软件测试网Ha4G`Q$W6r1dz"k
  3. importjava.util.ArrayList; 
  4. importjava.util.List; 

  5. .| |Q%CX(QQZT4a0
  6. publicclassFilterChainimplementsFilter { 
  7.     List<Filter> filters =newArrayList<Filter>(); 
  8.    intindex =0
  9. 51Testing软件测试网 ?"H a3@*k,_,Q#a
  10.    publicFilterChain addFilter(Filter f) { 
  11.        this.filters.add(f); 
  12.        returnthis
  13.     } 

  14. &@/~vO i.PU1s0
  15.    @Override
  16.    publicvoiddoFilter(Request request, Response response, FilterChain chain) { 
  17.        if(index == filters.size()) 
  18.            return
  19.         Filter f = filters.get(index); 
  20.         index++; 
  21.         f.doFilter(request, response, chain); 
  22.     } 
  23. }

  24. iE{v~I&t0
    51Testing软件测试网8^|4}?&|'[MG

      在FilterChain中继承了Filter接口,从而实现了doFilter方法,在FilterChain中又有一个index变量,该 变量是用来标记当前访问的是哪一个过滤器,这些过滤器是存放在ArrayList中的,这样用户在使用的时候就可以实现自己的过滤器,编写自己的处理逻 辑,从而将自己的过滤器添加到ArrayList中,再调用FilterChain的doFilter方法遍历整个责任链。51Testing软件测试网vn3[DZjK$e

    9g6Y}iWz;g0  下面我们编写三个过滤器:

    5W,v/EK"kG7P,f0

    ruSjps0  HTMLFilter类:

    z/~6~ |(z#}+n051Testing软件测试网i_:] aG k-h [

    ;Ykf/Z ZNp-Y0
    1. packagecom.lcq.filter; 
    2. 51Testing软件测试网jqzv asVq~:k T
    3. /**
    4. * 过滤HTML中的脚本元素
    5. * @author lcq
    6. *
    7. */
    8. publicclassHTMLFilterimplementsFilter { 
    9. 51Testing软件测试网"? U?8U%Ho(x5q%ve
    10.    @Override
    11.    publicvoiddoFilter(Request request, Response response,FilterChain chain) { 
    12.         request.requestStr = request.getRequestStr().replace("<","["
    13.                 .replace(">","] --------HTMLFilter"); 
    14.         chain.doFilter(request, response, chain); 
    15.         response.responseStr +="--------HTMLFilter"
    16.          
    17.     } 

    18. bO!Y{!WE0e\ K*pF7O0
    19. }
    51Testing软件测试网1p_,Pn S:h5T0zO

      SesitiveFilter类:

    g8K2P-h+k4[ ?051Testing软件测试网/T`v}D#ZDO

    ZZQ0D'`0
    1. packagecom.lcq.filter; 
    2. 51Testing软件测试网/ur|2G4Rz'h
    3. publicclassSesitiveFilterimplementsFilter { 

    4. :?sJ,mft#A~0
    5.    @Override
    6.    publicvoiddoFilter(Request request, Response response, FilterChain chain) { 
    7.         request.requestStr = request.getRequestStr().replace("敏感","  "
    8.                 .replace("猫猫","haha------SesitiveFilter"); 
    9.         chain.doFilter(request, response, chain); 
    10.         response.responseStr +="------SesitiveFilter"
    11. 51Testing软件测试网6SMF)Wkd
    12.     } 
    13. 51Testing软件测试网5h8qz%m i&^"\.|
    14. }
    51Testing软件测试网 zOl#_;g2P(B

      FaceFilter类:51Testing软件测试网T)| @U7| q `

    51Testing软件测试网.]"_"ZFG0|\Un

    I |~1?+_W0
    1. packagecom.lcq.filter; 
    2. 51Testing软件测试网n,sY;sHYU
    3. publicclassFaceFilterimplementsFilter { 
    4. 51Testing软件测试网7f)M'F QOg5P3|
    5.    @Override
    6.    publicvoiddoFilter(Request request, Response response, FilterChain chain) { 
    7.         request.requestStr = request.getRequestStr().replace(":)"
    8.                "^V^-------FaceFilter"); 
    9.         chain.doFilter(request, response, chain); 
    10.         response.responseStr +="-------FaceFilter"

    11. Q+bh}!ai1Neh0
    12.     } 

    13. PRbE:b6Z_%QO0
    14. }
    51Testing软件测试网KV F'H+[2C3v

      最后编写测试类:51Testing软件测试网(AQB TS9q

    51Testing软件测试网,s/?$Q/s ZY&]

    Jh p`)Q2P.u0
    1. packagecom.lcq.filter; 

    2. vVT9jf8G]0
    3. publicclassMain { 
    4.    publicstaticvoidmain(String[] args) { 
    5. String message ="敏感词汇,重庆,<script> 躲猫猫 :)"
    6. Request request =newRequest(); 
    7.         request.setRequestStr(message); 
    8.         Response response =newResponse(); 
    9.         response.setResponseStr("response"); 
    10.         FilterChain fc =newFilterChain(); 
    11.         fc.addFilter(newHTMLFilter()).addFilter(newSesitiveFilter()); 
    12. 51Testing软件测试网-iSSv^t9R%r
    13.         FilterChain fc2 =newFilterChain(); 
    14.         fc2.addFilter(newFaceFilter()); 
    15.         fc.addFilter(fc2); 
    16.         fc.doFilter(request, response,fc); 
    17.         System.out.println("request = "+ request.getRequestStr()); 
    18.         System.out.println("response = "+ response.getResponseStr()); 
    19.     } 

    20. !L3h(W^S*y0
    21. }
    51Testing软件测试网,VD0O.i!_'^&kk

      在上面的实例中应该注意两个地方:

    )g9UT B*o#C~ j051Testing软件测试网 ?4R(G,Hg7}@J

      1、我们建立的FilterChain中继承了Filter接口,所以在测试类中就可以像使用其他的过滤器一样使用FilterChain,大大提高了灵活性;

    oILfYTlU }0

    ] }B;_XM0  2、对于实现责任链的访问处理顺序问题,该问题的解决使用的是递归的思想,从而使先调用的结点在处理返回结果时其调用过滤器的顺序是相反的。这种解决方案在Struts和其他框架中实现过滤器和拦截器使用的较为普遍,并且十分巧妙。

    DxO;oe'vBTa0

TAG:

 

评分:0

我来说两句

Open Toolbar