标签:rup void 大小写 replace nbsp method 维护 cas inter
package club.interview.design_pattern.chapt9_chain; import java.util.ArrayList; import java.util.List; /** * 加工一个字符串 * 1. 过滤敏感字符 * 2. 修改大小写 * 3. 增加笑脸 * <p> * - v1. 手动加过滤器 * - v2. 用list装起来,for循环 * - v3. 用一个对象Chain封装起来,持有list ,做一个add方法,返回对象本身,链式调用 * <p> * * 需求新增:chain可以中断 * - v4. 接口返回boolean * * 需求新增: 模拟request response 多个链调用,chain.dofilter(request,response,chain) 自己控制调用时机 * - v5. 参考Servlet#Filter实现。此方法无返回值,每个diFilter方法自己调用chain的doFilter。组装者需要将所有的实现封装起来排序,发起第一个的调用即可,内部维护调用的index * - v6. 参考Spring的HandlerInterceptor * <p> * --- 番外:对比Spring的HandlerInterceptor和MethodInterceptor * 定义add方法 * * @author QuCheng on 2020/7/8. */ public class Chain { public static void main(String[] args) { Msg msg = new Msg(); msg.msg = "daxxxXXS--^_^kkksaafxardafa"; // v1(msg); // v2(msg); v3(msg); } private static void v1(Msg msg) { new Sensitive().doFilter(msg); new LowerUp().doFilter(msg); new Smile().doFilter(msg); System.out.println(msg.msg); } private static void v2(Msg msg) { List<Filter> filters = new ArrayList<>(); filters.add(new Sensitive()); filters.add(new LowerUp()); filters.add(new Smile()); filters.forEach(filter -> filter.doFilter(msg)); System.out.println(msg.msg); } private static void v3(Msg msg) { ChainFilter chainFilter = new ChainFilter(); chainFilter.addFilter(new Sensitive()). addFilter(new LowerUp()). addFilter(new Smile()); chainFilter.doFilter(msg); System.out.println(msg.msg); } } class Msg { public String msg; private String time; } class ChainFilter { List<Filter> filters = new ArrayList<>(); ChainFilter addFilter(Filter filter) { filters.add(filter); return this; } void doFilter(Msg msg) { for (Filter filter : filters) { if (!filter.doFilter(msg)) { return; } } } } interface Filter { boolean doFilter(Msg msg); } class Sensitive implements Filter { @Override public boolean doFilter(Msg msg) { msg.msg = msg.msg.replace("xxx", "xixixi"); return true; } } class LowerUp implements Filter { @Override public boolean doFilter(Msg msg) { msg.msg = msg.msg.toLowerCase(); return false; } } class Smile implements Filter { @Override public boolean doFilter(Msg msg) { msg.msg = msg.msg.replace("^_^", "<_^_>"); return true; } }
标签:rup void 大小写 replace nbsp method 维护 cas inter
原文地址:https://www.cnblogs.com/nightOfStreet/p/13269991.html