Twenty three design patterns of JAVA: Chain of Responsibility Pattern

Chain of Responsibility Pattern

concept

As the name suggests, the Chain of Responsibility Pattern creates a chain of receiver objects for requests. This mode gives the type of request and decouples the sender and receiver of the request. This type of design pattern belongs to behavioral pattern.

In this pattern, each recipient usually contains a reference to another recipient. If an object cannot process the request, it passes the same request to the next recipient, and so on.

introduce

Intent: avoid coupling the sender and receiver of the request, make it possible for multiple objects to receive the request, connect these objects into a chain, and pass the request along the chain until an object processes it.

Main solution: the handler in the responsibility chain is responsible for processing the request. The customer only needs to send the request to the responsibility chain without paying attention to the processing details of the request and the transmission of the request. Therefore, the responsibility chain decouples the sender of the request from the handler of the request.

When to use: filter many channels when processing messages.

How to solve it: all intercepted classes implement a unified interface.

Key code: the Handler aggregates itself and determines whether it is appropriate in the HandlerRequest. If the conditions are not met, it will be passed down and set before passing to whom.

Application examples: 1. The "beating drums and passing flowers" in the dream of Red Mansions. 2. Event bubbling in JS. 3. The processing of Encoding by Apache Tomcat in JAVA WEB, the interceptor of struts 2 and the Filter of jsp servlet.

Advantages: 1. Reduce the coupling degree. It decouples the sender and receiver of the request. 2. Simplifies objects. So that the object does not need to know the structure of the chain. 3. Enhance the flexibility of assigning responsibilities to objects. By changing the members in the chain or transferring their order, it is allowed to dynamically add or delete responsibilities. 4. It is convenient to add new request processing classes.

Disadvantages: 1. There is no guarantee that the request will be received. 2. The system performance will be affected to some extent, and it is inconvenient to debug the code, which may cause circular call. 3. It may not be easy to observe the characteristics of the runtime, which hinders debugging.

Usage scenario: 1. There are multiple objects that can handle the same request. The specific object that handles the request is automatically determined by the runtime. 2. Submit a request to one of multiple objects without explicitly specifying the recipient. 3. You can dynamically specify a set of objects to handle requests.

Note: there are many applications in JAVA WEB.

code

Implement string filtering

public interface Filter {
    String doFilter(String s);
}
public class FilterChain {


    private List<Filter> filters;


    public FilterChain() {
        filters = new ArrayList<>();
    }

    public List<Filter> getFilters() {
        return filters;
    }

    public String doFilter(String origin){
        for(Filter filter : filters){
            origin = filter.doFilter(origin);
        }
        return origin;
    }

    public FilterChain add(Filter newFilter) {
        filters.add(newFilter);
        return this;
    }

    public FilterChain add(FilterChain filterChain) {
        filters.addAll(filterChain.getFilters());
        return this;
    }
}

public class FilterDemo1 implements Filter{
    @Override
    public String doFilter(String s) {
        return s.replace("abc", "ABC");
    }
}

public class FilterDemo2 implements Filter{
    @Override
    public String doFilter(String s) {
        return s.replace("ha-ha", "haha");
    }
}

public class FilterDemo3 implements Filter {
    @Override
    public String doFilter(String s) {
        return s.replace("hey", "heihei");
    }
}

public class FilterDemo4 implements Filter{
    @Override
    public String doFilter(String s) {
        return s.replace("Huhu", "huhu");
    }
}

```java
public class TestChain {
    public static void main(String[] args) {
        String origin = "abc Haha, haha, haha, I'm Zhao Wenli, a primary school student";
        // All the filters are ready
        FilterDemo1 filterDemo1 = new FilterDemo1();

        String s = filterDemo1.doFilter(origin);
        System.out.println(s);
        //    result:
        //    ABC haha haha Hoo Hoo I'm Zhao Wenli primary school student

        //    Add all to filter chain
        FilterChain filterChain = new FilterChain();
        filterChain.add(filterDemo1);
        //    Add a filter at this time
        filterChain.add(new FilterDemo2());
        //     At this time, two filter s will be added
        filterChain.add(new FilterDemo2())
                .add(new FilterDemo3())
                .add(new FilterDemo4());
        String s1 = filterChain.doFilter(origin);
        System.out.println(s1);
        //    result:
        //    ABC haha, haha, haha, I'm Zhao Wenli, a primary school student
        //Ab chahaiheihuhu, I'm Zhao Wenli, a primary school student

        // Add a filterChain at this time
        String origin1 = " abc Haha, haha, haha, I'm Zhao Wenli, a primary school student";
        FilterChain filterChain1 = new FilterChain();
        FilterChain filterChain2 = new FilterChain();
        filterChain1.add(new FilterDemo1())
                .add(new FilterDemo2());
        filterChain2.add(new FilterDemo3())
                .add(new FilterDemo4());
        filterChain1.add(filterChain2);
        String s2 = filterChain1.doFilter(origin1);
        System.out.println(s2);
        //    result:
        //    ABC haha, haha, haha, I'm Zhao Wenli, a primary school student
        //Ab chahaiheihuhu, I'm Zhao Wenli, a primary school student
        // Ab chahaiheihuhu, I'm Zhao Wenli, a primary school student
    }

}

Keywords: Java Design Pattern

Added by Hybride on Sun, 06 Feb 2022 06:17:42 +0200