责任链模式

责任链模式

顾名思义,责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。

在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。

意图:避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。

主要解决:职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无须关心请求的处理细节和请求的传递,所以职责链将请求的发送者和请求的处理者解耦了。

何时使用:在处理消息的时候以过滤很多道。

如何解决:拦截的类都实现统一接口。

上代码

//责任链 模式
public class ChainOfResponsibility {

    public static void main(String[] args) {
        Msg msg = new Msg();
        msg.setMsg("Hello World!:) <script>alert(1)</script> 都是nt tmd");
        //过滤器链
        FilterChain fc1 = new FilterChain();
        //添加过滤器
        fc1.addFilter(new HTMLFilter()).addFilter(new SensitiveFilter());
        //过滤器链
        FilterChain fc2 = new FilterChain();
        //添加过滤器
        fc2.addFilter(new FaceFilter());
        //添加到第一个过滤链上
        fc1.addFilter(fc2);
        //执行过滤链
        fc1.doFilter(msg,fc1);
        //查看结果
        System.out.println(msg.getMsg());

    }
}

//被处理的对象 这里代替request
class Msg{
    private String msg;

    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}
//过滤器接口
interface Filter{
    void doFilter(Msg msg,FilterChain filterChain);
}

//html 过滤器 过滤xss
class HTMLFilter implements Filter{
    @Override
    public void doFilter(Msg msg,FilterChain filterChain) {
        String msg1 = msg.getMsg();
        msg1 = msg1.replace('<','[');
        msg1 = msg1.replace('>',']');
        msg.setMsg(msg1);
        filterChain.doFilter(msg,filterChain);
    }
}
//笑脸过滤器
class FaceFilter implements Filter{
    @Override
    public void doFilter(Msg msg,FilterChain filterChain) {
        String msg1 = msg.getMsg();
        msg1 = msg1.replace(":)","-_-");
        msg.setMsg(msg1);
        filterChain.doFilter(msg,filterChain);
    }
}
//敏感词过滤器
class SensitiveFilter implements Filter{
    @Override
    public void doFilter(Msg msg,FilterChain filterChain) {
        String msg1 = msg.getMsg();
        msg1 = msg1.replace("nt","***");
        msg1 = msg1.replace("tmd","***");
        msg.setMsg(msg1);
        filterChain.doFilter(msg,filterChain);
    }
}
//过滤链
class FilterChain implements Filter{
    List<Filter> filters = new ArrayList<>();
    int index = 0;

    public FilterChain addFilter(Filter filter){
        filters.add(filter);
        return this;
    }
    @Override
    public void doFilter(Msg msg,FilterChain filterChain){
        if (index >= filters.size()) return;
        Filter filter = filters.get(index);
        index++;
        filter.doFilter(msg,filterChain);
    }

过滤后的信息 !!

posted @ 2021-06-08 14:16  immortal_mode  阅读(31)  评论(0)    收藏  举报