package com.macrotea.responzchain.interfazz; public interface Filter { public String doFilter(String text); }
package com.macrotea.responzchain.impl; import com.macrotea.responzchain.interfazz.Filter; public class HTMLFilter implements Filter { @Override public String doFilter(String text) { String retVal = null; retVal = text.replaceAll("<[^>]+>", ""); return retVal; } }
package com.macrotea.responzchain.impl; import com.macrotea.responzchain.interfazz.Filter; public class HarmonyFilter implements Filter { private static final String[] disHarmonyWords = { "大乡里", "犀利哥", "奔跑哥" }; @Override public String doFilter(String text) { String retVal = text; for (String word : disHarmonyWords) { retVal=retVal.replaceAll(word, "*"); } return retVal; } }
package com.macrotea.responzchain.chain; import java.util.ArrayList; import java.util.List; import com.macrotea.responzchain.interfazz.Filter; public class FilterChain { private List<Filter> filters; public FilterChain() { super(); filters = new ArrayList<Filter>(); } public FilterChain appendFilter(Filter filter) { filters.add(filter); return this; } public FilterChain removeFilter(Filter filter) { filters.remove(filter); return this; } public String executeChain(String text) { String retVal = text; for (Filter filter : filters) { retVal = filter.doFilter(retVal); } return retVal; } }
package com.macrotea.responzchain.interfazz; public interface Handler { public String doHandle(String text); }
package com.macrotea.responzchain.handler; import com.macrotea.responzchain.chain.FilterChain; import com.macrotea.responzchain.interfazz.Handler; public class MessageHandler implements Handler{ private FilterChain filterChain; public FilterChain getFilterChain() { return filterChain; } public void setFilterChain(FilterChain filterChain) { this.filterChain = filterChain; } public MessageHandler(FilterChain filterChain) { super(); this.filterChain = filterChain; } @Override public String doHandle(String text) { return filterChain.executeChain(text); } }
package com.macrotea.responzchain.test; import com.macrotea.responzchain.chain.FilterChain; import com.macrotea.responzchain.handler.MessageHandler; import com.macrotea.responzchain.impl.HTMLFilter; import com.macrotea.responzchain.impl.HarmonyFilter; public class Mainer { public static void main(String[] args) { String netText="<h1>哈哈</h1>我来到一个神奇的地方,这里有犀利哥,有大乡里,有奔跑哥,什么都有!"; /*构造过滤器链*/ FilterChain chain=new FilterChain(); chain.appendFilter(new HTMLFilter()) .appendFilter(new HarmonyFilter()); /*传递给信息处理者*/ MessageHandler msgHandler =new MessageHandler(chain); String clearText=msgHandler.doHandle(netText); System.out.println(clearText); } }
简单责任链设计模式!!