First, the goal
Add Filterchain function
Second, the Code
1.filter.java
1 Public Interface Filter {2 Public string DoFilter (String str); 3 }
2.filterchain.java
1 Importjava.util.ArrayList;2 Importjava.util.List;3 4 Public classFilterchainImplementsFilter {5 6 Privatelist<filter> filters =NewArraylist<filter>();7 8 Publicstring DoFilter (String str) {9 for(Filter f:filters) {Tenstr =f.dofilter (str); One } A returnstr; - } - the //set the return value of the function to Filterchain, and return this to make it easy to write code in a chained style - PublicFilterchain AddFilter (filter filter) { - Filters.add (filter); - return This; + } - +}
3.htmlfilter.java
1 Public class Implements Filter {23 @Override4public String DoFilter (String str) {5 return str.replace (' < ', ' ['). Replace (">", "]"); 6 }78 }
4.sensitivefilter.java
1 Public class Implements Filter {23 @Override4public String DoFilter (String str) {5 return str.replace ("sensitive", "happiness"); 6 }78 }
5.msgprocessor.java
1 Public classMsgprocessor {2 3 //Private List<filter> filters = new arraylist<filter> ();4 Filterchain Filterchain;5 PrivateString msg;6 7 PublicFilterchain Getfilterchain () {8 returnFilterchain;9 }Ten One Public voidSetfilterchain (Filterchain filterchain) { A This. Filterchain =Filterchain; - } - the - PublicString getmsg () { - returnmsg; - } + - Public voidsetmsg (String msg) { + This. msg =msg; A } at - PublicString process () { - returnFilterchain.dofilter (msg); - } -}
6.test.java
1 Public classTest {2 3 @org. Junit.test4 Public voidTestfilter () {5 6Msgprocessor processor =Newmsgprocessor ();7 8String msg = "; 9 processor.setmsg (msg);Ten OneFilterchain FC1 =NewFilterchain (); AFc1.addfilter (NewHtmlfilter ()); - -Filterchain FC2 =NewFilterchain (); theFc2.addfilter (NewSensitivefilter ()); - - //since Filterchain implements the filter interface, Filterchain is also a filter, so you can call addfilter to add FC2 - Fc1.addfilter (FC2); + - Processor.setfilterchain (FC1); + AString result =processor.process (); at System.out.println (result); - - } - -}
Iii. Results of operation
Java Responsibility Filterchain